Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

as_date

Convert an object to a date or date-time


Description

Convert an object to a date or date-time

Usage

as_date(x, ...)

## S4 method for signature 'ANY'
as_date(x, ...)

## S4 method for signature 'POSIXt'
as_date(x, tz = NULL)

## S4 method for signature 'numeric'
as_date(x, origin = lubridate::origin)

## S4 method for signature 'character'
as_date(x, tz = NULL, format = NULL)

as_datetime(x, ...)

## S4 method for signature 'POSIXt'
as_datetime(x, tz = "UTC")

## S4 method for signature 'numeric'
as_datetime(x, origin = lubridate::origin, tz = "UTC")

## S4 method for signature 'character'
as_datetime(x, tz = "UTC", format = NULL)

## S4 method for signature 'ANY'
as_datetime(x, tz = "UTC")

Arguments

x

a vector of POSIXt, numeric or character objects

...

further arguments to be passed to specific methods (see above).

tz

a time zone name (default: time zone of the POSIXt object x). See OlsonNames().

origin

a Date object, or something which can be coerced by as.Date(origin, ...) to such an object (default: the Unix epoch of "1970-01-01"). Note that in this instance, x is assumed to reflect the number of days since origin at "UTC".

format

format argument for character methods. When supplied parsing is performed by strptime(). For this reason consider using specialized parsing functions in lubridate.

Value

a vector of Date objects corresponding to x.

Compare to base R

These are drop in replacements for as.Date() and as.POSIXct(), with a few tweaks to make them work more intuitively.

  • Called on a POSIXct object, as_date() uses the tzone attribute of the object to return the same date as indicated by the printed representation of the object. This differs from as.Date, which ignores the attribute and uses only the tz argument to as.Date() ("UTC" by default).

  • Both functions provide a default origin argument for numeric vectors.

  • Both functions will generate NAs for invalid date format. A warning message will provide a count of the elements that were not converted

  • as_datetime() defaults to using UTC.

Examples

dt_utc <- ymd_hms("2010-08-03 00:50:50")
dt_europe <- ymd_hms("2010-08-03 00:50:50", tz="Europe/London")
c(as_date(dt_utc), as.Date(dt_utc))
c(as_date(dt_europe), as.Date(dt_europe))
## need not supply origin
as_date(10)
## Will replace invalid date format with NA
dt_wrong <- c("2009-09-29", "2012-11-29", "2015-29-12")
as_date(dt_wrong)

lubridate

Make Dealing with Dates a Little Easier

v1.7.10
GPL (>= 2)
Authors
Vitalie Spinu [aut, cre], Garrett Grolemund [aut], Hadley Wickham [aut], Ian Lyttle [ctb], Imanuel Costigan [ctb], Jason Law [ctb], Doug Mitarotonda [ctb], Joseph Larmarange [ctb], Jonathan Boiser [ctb], Chel Hee Lee [ctb], Google Inc. [ctb, cph]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.