日期加减

基本类型 / 日期和时间

# A fixed moment: the output stays the same
moment <- as.POSIXct("2027-01-01 22:13:20",
                     tz = "UTC")

# POSIXct counts in seconds
in_one_hour <- moment + 3600

# A Date counts in days
day <- as.Date(moment)
yesterday <- day - 1
tomorrow <- day + 1

# by = "month" and "year" step by the calendar
by_month <- seq(day, by = "month", length.out = 3)
by_year <- seq(day, by = "year", length.out = 2)

# Trap: the 31st moves on into March
from_jan31 <- seq(as.Date("2027-01-31"),
                  by = "month", length.out = 3)

cat("moment =", format(moment), "\n")
cat("in_one_hour =", format(in_one_hour), "\n")
cat("yesterday =", format(yesterday), "\n")
cat("tomorrow =", format(tomorrow), "\n")
cat("by_month =", format(by_month), "\n")
cat("by_year =", format(by_year), "\n")
cat("from_jan31 =", format(from_jan31), "\n")