fymd {fastymd} | R Documentation |
Construct dates from character and numeric input
Description
fymd()
is a generic for validated conversion of R objects to (integer)
Date
. Efficient methods are provided for numeric
and character
inputs.
Usage
fymd(...)
## Default S3 method:
fymd(...)
## S3 method for class 'numeric'
fymd(y, m = 1, d = 1, ...)
## S3 method for class 'character'
fymd(x, strict = FALSE, ...)
Arguments
... |
Arguments to be passed to or from other methods. |
y , m , d |
Numeric vector corresponding to the desired years, months and days. Double vectors are coerced to integer. Length 1 vectors will be recycled to the common size across |
x |
Vector of year-month-date strings in a numeric format (e.g. "2020-02-01"). Parses digits separated by non-digits. Leading and trailing whitespace will be ignored. |
strict |
Should non-whitespace output after a valid date be allowed?
|
Details
The underlying algorithm for both the numeric and character methods follow the approach described in Hinnant (2021) for calculating days from the UNIX Epoch from Gregorian Calendar dates.
The character version parses inputs in a fixed, year, month and day order.
These values must be digits but can be separated by any non-digit character.
It is similar in spirit to that of Simon Urbanek's fastDate()
implementation in that we use pure text parsing and no system calls.
fymd()
differs from fastDate()
in that it
validates all dates for correctness and supports a a much larger range of
dates (i.e. the Proleptic Gregorian calendar.
This additional capability does come with a small performance cost but, IMO,
remains competetive.
For both numeric and character versions years must be in the range
[-9999, 9999]
.
Value
A Date
object
References
Hinnant, H. (2021) chrono-Compatible Low-Level Date Algorithms. Available at: https://howardhinnant.github.io/date_algorithms.html#days_from_civil (Accessed 17 April 2025).
Urbanek S (2022). fasttime: Fast Utility Function for Time Parsing and Conversion. R package version 1.1-0, doi:10.32614/CRAN.package.fasttime.
Examples
cdate <- "2025-04-16"
timestamp <- "2025-04-16T09:45:53+0000"
# Ignoring the time element
fymd(timestamp)
# This will return NA with a warning
fymd(timestamp, strict = TRUE)
# Checking
as.Date(cdate) == fymd(timestamp)
# Leap year
fymd(2020, 2, 29)
# Not a leap year
fymd(2021, 2, 29)