tidyverse / lubridate

Make working with dates in R just that little bit easier
https://lubridate.tidyverse.org
GNU General Public License v3.0
724 stars 207 forks source link

Lubridate months() not doing period arithmetic #1128

Closed rhgof closed 1 year ago

rhgof commented 1 year ago

Really simple date - period - should equal a date works except when using months() see below

# insert reprex here
``` r
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
R.version.string 
#> [1] "R version 4.2.1 (2022-06-23)"
packageVersion("lubridate")
#> [1] '1.9.2'
now()
#> [1] "2023-07-31 15:52:51 AEST"
days(1)
#> [1] "1d 0H 0M 0S"
months(1)
#> [1] "1m 0d 0H 0M 0S"

now() - days(1)
#> [1] "2023-07-30 15:52:51 AEST"
now() - years(1)
#> [1] "2022-07-31 15:52:51 AEST"
now() - months(1)
#> [1] NA
!is.na(now()-days(1))   #TRUE
#> [1] TRUE
!is.na(now()-months(1)) #FALSE
#> [1] FALSE
!is.na(now()-lubridate::months(1)) #ERROR
#> Error: 'months' is not an exported object from 'namespace:lubridate'

Created on 2023-07-31 with reprex v2.0.2

vspinu commented 1 year ago

This is how arithmetic operations with periods work by default in lubridate - if the results ends on a non-existing date the result is NA. Use %m-% instead.