lubridate (version 1.5.0)

round_date: Round, flour and ceiling methods for date-time objects.

Description

Users can specify whether to round to the nearest second, minute, hour, day, week, month, quarter, or year.

Usage

round_date(x, unit = c("second", "minute", "hour", "day", "week", "month",
  "year", "quarter"))

floor_date(x, unit = c("second", "minute", "hour", "day", "week", "month", "year", "quarter"))

ceiling_date(x, unit = c("second", "minute", "hour", "day", "week", "month", "year", "quarter"))

Arguments

x
a vector of date-time objects
unit
a character string specifying the time unit to be rounded to. Should be one of "second", "minute", "hour", "day", "week", "month", "quarter", or "year."

Value

  • x with the appropriate units floored

Details

round_date takes a date-time object and rounds it to the nearest integer value of the specified time unit. For rounding date-ties which is exactly halfway between two consecutive units, the convention is to round up. Note that this is in line with the behavior of R's base round.POSIXt function but does not follow the convention of the base round function which "goes to the even digit" per IEC 60559.

floor_date takes a date-time object and rounds it down to the nearest integer value of the specified time unit.

ceiling_date takes a date-time object and rounds it up to the nearest integer value of the specified time unit.

By convention the boundary for a month is the first second of the month. Thus floor_date(ymd("2000-03-01"), "month") gives "2000-03-01 UTC".

See Also

round

Examples

Run this code
x <- as.POSIXct("2009-08-03 12:01:59.23")
round_date(x, "second")
# "2009-08-03 12:01:59 CDT"
round_date(x, "minute")
# "2009-08-03 12:02:00 CDT"
round_date(x, "hour")
# "2009-08-03 12:00:00 CDT"
round_date(x, "day")
# "2009-08-04 CDT"
round_date(x, "week")
# "2009-08-02 CDT"
round_date(x, "month")
# "2009-08-01 CDT"
round_date(x, "quarter")
# "2009-07-01 CDT"
round_date(x, "year")
# "2010-01-01 CST"

x <- as.POSIXct("2009-08-03 12:01:59.23")
floor_date(x, "second")
# "2009-08-03 12:01:59 CDT"
floor_date(x, "minute")
# "2009-08-03 12:01:00 CDT"
floor_date(x, "hour")
# "2009-08-03 12:00:00 CDT"
floor_date(x, "day")
# "2009-08-03 CDT"
floor_date(x, "week")
# "2009-08-02 CDT"
floor_date(x, "month")
# "2009-08-01 CDT"
floor_date(x, "quarter")
# "2009-07-01 CDT"
floor_date(x, "year")
# "2009-01-01 CST"

x <- as.POSIXct("2009-08-03 12:01:59.23")
ceiling_date(x, "second")
# "2009-08-03 12:02:00 CDT"
ceiling_date(x, "minute")
# "2009-08-03 12:02:00 CDT"
ceiling_date(x, "hour")
# "2009-08-03 13:00:00 CDT"
ceiling_date(x, "day")
# "2009-08-04 CDT"
ceiling_date(x, "week")
# "2009-08-09 CDT"
ceiling_date(x, "month")
# "2009-09-01 CDT"
ceiling_date(x, "quarter")
# "2009-10-01 CDT"
ceiling_date(x, "year")
# "2010-01-01 CST"

Run the code above in your browser using DataCamp Workspace