Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding lubridate dates to vector changes timezone and thus date

Tags:

date

r

lubridate

In the R package lubridate, I can easily create a date with the following syntax:

> mdy("5/4/2015")

As expected, it produces the following result:

[1] "2015-05-04 UTC"

However, if I try to add that very value to an array, it seems to change from UTC to my local time (EDT):

> c(mdy("5/4/2015"))
[1] "2015-05-03 20:00:00 EDT"

Since I don't care about times this wouldn't affect me much except that this results in the date shifting back by 1, as follows:

> day(mdy("5/4/2015"))
[1] 4
> day(c(mdy("5/4/2015")))
[1] 3

To me, the act of adding something to an array should not change the value of that something. Am I missing something here, and is there a way to resolve this issue?

like image 825
Michael McGowan Avatar asked May 05 '15 01:05

Michael McGowan


Video Answer


1 Answers

That's because lubridate::mdy assumes UTC. When you wrap it around c(), it reverts back to your local timezone EDT because c() does not pass on the timezone attribute:

> attr(mdy("5/4/2015", tz = "EDT"), "tzone")
# [1] "EDT"
> attr(c(mdy("5/4/2015", tz = "EDT")), "tzone")
# NULL

You can do:

Sys.setenv(TZ = "UTC")

To set your local timezone to UTC.

Alternatively, you can specity the timezone explicitly in mdy():

mdy("5/4/2015", tz = "UTC")
like image 142
Steven Beaupré Avatar answered Sep 23 '22 01:09

Steven Beaupré