Lubridate::round_date() does not accept date

I'm learning the R package lubridate. I discovered that the round_date() function does not provide the correct answer when the input is a date. The input must be a datetime. floor_date() and ceiling_date() have no such problem.

For example,
date1 <- as_datetime("2022-09-23")
date2 <- as_datetime("2022-05-19")
round_date(date1, "year")
#> [1] "2023-01-01 UTC"
round_date(date2, "year")
#> [1] "2022-01-01 UTC"

date3 <- as_date("2022-09-23")
date4 <- as_date("2022-05-19")
round_date(date3, "year")
#> [1] "2022-01-01"
round_date(date4, "year")
#> [1] "2022-01-01"

What gives? Do I miss out something?

Hello @lesoch ,
the documentation (?lubridate::round_date) explicitly mentions that the first argument has to be a date-time object. However at the end of the docs it also mentions Rounding Up Date Objects.

The variables date3 and date4 have class Date.

Looking in the code (displaying lubridate::round_date) I see that internally the variables above , mid and below are created. In your case the mid variable is not in the range between below and above . I suspect that this is not correct and that the assignment for mid should read:

mid <- unclass(as.POSIXct(x)) 

So you are right that the function does not perform as you had expected.

The (easy) solution: always transform your variables with as_datetime before rounding:

round_date(as_datetime(date3), "year")

Thanks for your quick reply. I have no issue with using datetime instead of date. What puzzled me as a R beginner is its inconsistency with floor_date() and ceiling_date() which work correctly with date input.

This is already solved on the development version of lubridate (not yet released to CRAN).

date3 <- as_date("2022-09-23")
date4 <- as_date("2022-05-19")

round_date(date3, "year")
#> [1] "2023-01-01"

round_date(date4, "year")
#> [1] "2022-01-01"

Created on 2022-10-08 with reprex v2.0.2

You can install it from GitHub


Thanks for your help. RStudio community is a helpful place to be in.

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.