r-lib / clock

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

invalid = "previous" working for `add_months()` but not for `add_days()` #368

Closed balthasars closed 2 months ago

balthasars commented 2 months ago

Hi there!

Thank you for your great work on this useful and refined package, I love how strict it is 🙂

Using this package in practice, I've encountered a behavior can't quite wrap my ahead around : How come invalid = "previous" will work for add_months() but not for add_days()?

example_dt <- as.POSIXct("2018-01-31 12:00:00", tz = "GMT")
clock::add_days(x = example_dt, n = 1, invalid = "previous-day")
#> Error in `clock::add_days()`:
#> ! `...` must be empty.
#> ✖ Problematic argument:
#> • invalid = "previous-day"
clock::add_days(x = example_dt, n = 1, invalid = "previous")
#> Error in `clock::add_days()`:
#> ! `...` must be empty.
#> ✖ Problematic argument:
#> • invalid = "previous"

clock::add_months(x = example_dt, n = 1, invalid = "previous")
#> [1] "2018-02-28 23:59:59 GMT"
clock::add_months(x = example_dt, n = 1, invalid = "previous-day")
#> [1] "2018-02-28 12:00:00 GMT"

Created on 2024-04-10 with reprex v2.1.0

Thanks in advance and best, Balthasar

DavisVaughan commented 2 months ago

For POSIXct (R date-times), invalid is specific to handling invalid day of the month issues. Meaning if you take 2018-03-31 and subtract 1 month (literally, change the 3 to a 2), you end up with 2018-02-31, which is invalid because that combination of components doesn't make up a valid date. Then invalid lets you describe how you'd like to handle that.

Because it's specific to day of the month issues, the problem of invalid days can only occur when doing arithmetic at a less precise precision than day (i.e. year or month arithmetic). When you add 1 day to 2018-02-28, you get 2018-03-01, there is never any ambiguity to deal with.

Even in the case of something like add_days(as.Date("2018-03-31"), -31) there is no ambiguity. You get 2018-02-28!

So, since it can never be an issue, it isn't an argument to that function