date_parse | R Documentation |
date_parse()
parses strings into a Date.
The default format
used is "%Y-%m-%d"
. This matches the default
result from calling print()
or format()
on a Date.
date_parse(x, ..., format = NULL, locale = clock_locale())
x |
A character vector to parse. |
... |
These dots are for future extensions and must be empty. |
format |
A format string. A combination of the following commands, or A vector of multiple format strings can be supplied. They will be tried in the order they are provided. Year
Month
Day
Day of the week
ISO 8601 week-based year
Week of the year
Day of the year
Date
Time of day
Time zone
Miscellaneous
|
locale |
A locale object created from |
date_parse()
ignores both the %z
and %Z
commands, as clock treats
Date as a naive type, with a yet-to-be-specified time zone.
Parsing strings with sub-daily components, such as hours, minutes, or
seconds, should generally be done with date_time_parse()
. If you only
need the date components from a string with sub-daily components, choose
one of the following:
If the date components are at the front of the string, and you don't want
the time components to affect the date in any way, you can use
date_parse()
to parse only the date components. For example,
date_parse("2019-01-05 00:01:02", format = "%Y-%m-%d")
will parse
through 05
and then stop.
If you want the time components to influence the date, then parse the full
string with date_time_parse()
, round to day precision with a
rounding function like date_round()
, and cast to date with as_date()
.
Attempting to directly parse all components of a sub-daily string into a
Date is ambiguous and undefined, and is unlikely to work as you might expect.
For example, date_parse("2019-01-05 00:01:02", format = "%Y-%m-%d %H:%M:%S")
is not officially supported, even if it works in
some cases.
A Date.
date_parse("2020-01-01")
date_parse(
"January 5, 2020",
format = "%B %d, %Y"
)
# With a different locale
date_parse(
"janvier 5, 2020",
format = "%B %d, %Y",
locale = clock_locale("fr")
)
# A neat feature of `date_parse()` is the ability to parse
# the ISO year-week-day format
date_parse("2020-W01-2", format = "%G-W%V-%u")
# ---------------------------------------------------------------------------
# Sub-daily components
# If you have a string with sub-daily components, but only require the date,
# first parse them as date-times to fully parse the sub-daily components,
# then round using whatever convention is required for your use case before
# converting to date.
x <- c("2019-01-01 11", "2019-01-01 12")
x <- date_time_parse(x, zone = "UTC", format = "%Y-%m-%d %H")
x
date_floor(x, "day")
date_round(x, "day")
as_date(date_round(x, "day"))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.