0

I stumbled upon a quite surprising behavior of the as.Date function, when I converted an innocent string:

d0 <- "05-06-20" # my innocent date string for the fifth of June 2020
d1 <- as.POSIXct(d0, format="%d-%m-%y")  # Converted to "2020-06-05 CEST", containing time zone
d2 <- as.Date(d1) # "2020-06-04", it has moved one day back, when I just want the date
d3 <- anytime::anydate(d1) # "2020-06-05" gives the correct conversion

Can anyone explain why as.Date gets it wrong?

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252  
mondano
  • 827
  • 10
  • 29
  • If you do `as.POSIXct(..., tz="UTC")`, all works. When converting from `POSiXt` to `Date`, it does rounding, so you need to be cognizant of TZ when making conversions. – r2evans Sep 04 '20 at 15:26
  • Is there a reason you cannot do `as.Date("05-06-20", format="%d-%m-%y")` directly? – r2evans Sep 04 '20 at 15:26
  • 1
    I could do this directly, the code just "grew organically" and I stumbled upon this behavior. Still, I don't understand why rounding from CEST would make it one day earlier. How does this work? – mondano Sep 04 '20 at 15:30

0 Answers0