Learn R Programming

fastymd (version 0.1.4)

fymd: 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(...)

# S3 method for default fymd(...)

# S3 method for numeric fymd(y, m = 1, d = 1, ...)

# S3 method for character fymd(x, strict = FALSE, ...)

Value

A Date object

Arguments

...

Arguments to be passed to or from other methods.

y, m, d

integerish.

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 y, m and d.

x

character.

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

bool.

Should non-whitespace output after a valid date be allowed?

FALSE (default) will ignore output after a valid date whereas TRUE will reject said strings, returning NA.

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].

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, tools:::Rd_expr_doi("10.32614/CRAN.package.fasttime").

Examples

Run this code

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)

Run the code above in your browser using DataLab