Skip to contents

Checks whether a vector can be coerced to a base::Date without losing information, returning it silently if so. Otherwise an informative error message is signaled.

Usage

to_date(
  x,
  ...,
  x_arg = caller_arg(x),
  call = caller_env(),
  x_class = object_type(x)
)

# S3 method for class '`NULL`'
to_date(x, ..., allow_null = TRUE, x_arg = caller_arg(x), call = caller_env())

# S3 method for class 'character'
to_date(
  x,
  ...,
  x_arg = caller_arg(x),
  call = caller_env(),
  x_class = object_type(x)
)

# S3 method for class 'factor'
to_date(
  x,
  ...,
  x_arg = caller_arg(x),
  call = caller_env(),
  x_class = object_type(x)
)

# S3 method for class 'POSIXct'
to_date(x, ...)

# S3 method for class 'POSIXlt'
to_date(x, ...)

# S3 method for class 'numeric'
to_date(x, ...)

# S3 method for class 'integer'
to_date(x, ...)

Arguments

x

The object to stabilize.

...

Arguments passed to methods.

x_arg

(character(1)) The name of the object being stabilized to use in error messages. The automatic value will work in most cases, or pass it through from higher-level functions to make error messages clearer in unexported functions.

call

(environment) The execution environment to mention as the source of error messages.

x_class

(character(1)) The class name of the object being stabilized to use in error messages. Use this if you remove a special class from the object before checking its coercion, but want the error message to match the original class.

allow_null

(logical(1)) Is NULL an acceptable value?

Value

The input as a base::Date vector.

Details

Character vectors must use the RFC 3339 full-date format ("YYYY-MM-DD"); any other shape (such as "11/13/2018") is rejected (but see stabilize_date()). POSIXct and POSIXlt values are truncated to their date component, discarding the time-of-day and timezone offset. Numeric and integer values are treated as the number of days since the Unix epoch ("1970-01-01").

Examples

to_date(as.Date("2024-01-01"))
#> [1] "2024-01-01"
to_date("2024-01-01")
#> [1] "2024-01-01"
to_date(c("2024-01-01", NA))
#> [1] "2024-01-01" NA          
to_date(0L)
#> [1] "1970-01-01"
to_date(as.POSIXct("2024-01-01 23:00:00", tz = "UTC"))
#> [1] "2024-01-01"
to_date(NULL)
#> NULL
try(to_date("11/13/2018"))
#> Error in eval(expr, envir) : 
#>   `"11/13/2018"` <character> must be coercible to <date>
#>  Can't convert some values due to invalid or ambiguous date format.
#>  Locations: 1
#>  Values: "11/13/2018"
try(to_date(c("2024-01-01", "not-a-date")))
#> Error in eval(expr, envir) : 
#>   `c("2024-01-01", "not-a-date")` <character> must be coercible to <date>
#>  Can't convert some values due to invalid or ambiguous date format.
#>  Locations: 2
#>  Values: "not-a-date"