r-lib / clock

A Date-Time Library for R
https://clock.r-lib.org
Other
102 stars 5 forks source link

Document the fact that you can create dates out of relative order with `add_days()` #283

Closed DavisVaughan closed 1 year ago

DavisVaughan commented 2 years ago

We wanted to avoid this as much as possible, but with POSIXt and time zones, you can't avoid this.

And say that add_hours() is the solution if you stay in POSIXct. Or you can switch to sys-time and use add_days() there.

See if there is a nonexistent time issue like this too.

library(clock)
library(lubridate, warn.conflicts = FALSE)

x <- c(
  date_time_build(2012, 4, 1, 2, 30, zone = "Australia/Melbourne", ambiguous = "earliest"),
  date_time_build(2012, 4, 1, 2, 00, zone = "Australia/Melbourne", ambiguous = "latest"),
  date_time_build(2012, 4, 1, 2, 30, zone = "Australia/Melbourne", ambiguous = "latest")
)
x
#> [1] "2012-04-01 02:30:00 AEDT" "2012-04-01 02:00:00 AEST"
#> [3] "2012-04-01 02:30:00 AEST"

# DST fallback from 02:59:59 AEDT -> 02:00:00 AEST on this day

# So this can produce a vector of dates out of relative order
add_days(x, -1)
#> [1] "2012-03-31 02:30:00 AEDT" "2012-03-31 02:00:00 AEDT"
#> [3] "2012-03-31 02:30:00 AEDT"
add_months(x, -1)
#> [1] "2012-03-01 02:30:00 AEDT" "2012-03-01 02:00:00 AEDT"
#> [3] "2012-03-01 02:30:00 AEDT"

x - days(1)
#> [1] "2012-03-31 02:30:00 AEDT" "2012-03-31 02:00:00 AEDT"
#> [3] "2012-03-31 02:30:00 AEDT"
x - months(1)
#> [1] "2012-03-01 02:30:00 AEDT" "2012-03-01 02:00:00 AEDT"
#> [3] "2012-03-01 02:30:00 AEDT"

Created on 2021-12-24 by the reprex package (v2.0.1)