Skip to content

Add make_date() feature for converting date-times into dates #355

@huftis

Description

@huftis

I propose adding a convenience function make_date() for converting date-times to dates. One might by tempted to use as.Date(), and this works in many cases, but with the default options it gives surprising results in a few cases. Example:

x1 = as.POSIXct("2010-08-03 00:59:59.23")
x2 = as.POSIXct("2010-08-03 00:59:59.23", tz="Europe/London")
x3 = as.POSIXct("2010-11-03 00:59:59.23")
x4 = as.POSIXct("2010-11-03 00:59:59.23", tz="Europe/London")

The naïve user might expect as.Date() to return the 3rd of the month (August/November) for all of x1x4. However, on my system (a Europe/Oslo timezone), I get:

> as.Date(x1)
[1] "2010-08-02"
> as.Date(x2)
[1] "2010-08-02"
> as.Date(x3)
[1] "2010-11-02"
> as.Date(x4)
[1] "2010-11-03"

It’s even more surprising if you have already used floor_date(x, "day") on the objects to remove the ‘time’ part.

The way to get the correct date (Date) corresponding to a date-time is either as.Date(format(x, "%Y-%m-%d")) or (preferably) as.Date(x, tz=attr(x, "tzone")):

> as.Date(x1, tz=attr(x1, "tzone"))
[1] "2010-08-03"
> as.Date(x2, tz=attr(x2, "tzone"))
[1] "2010-08-03"
> as.Date(x3, tz=attr(x3, "tzone"))
[1] "2010-11-03"
> as.Date(x4, tz=attr(x4, "tzone"))
[1] "2010-11-03"

So I propose adding such a convenience function make_date() to lubridate, that would run

as.Date(x, tz=attr(x, "tzone"))

for POSIXct and POSIXlt objects (and just return x for Date() objects).

I just based the name on the make_difftime() function; other names may better.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions