为日期增加天数

我有一个日期,我想增加天,以便找到一些未来的日期。

例如,我如何找到2001年1月1日后45天的日期?

133012 次浏览

Use +

> as.Date("2001-01-01") + 45
[1] "2001-02-15"

Just use

 as.Date("2001-01-01") + 45

from base R, or date functionality in one of the many contributed packages. My RcppBDT package wraps functionality from Boost Date_Time including things like 'date of third Wednesday' in a given month.

Edit: And egged on by @Andrie, here is a bit more from RcppBDT (which is mostly a test case for Rcpp modules, really).

R> library(RcppBDT)
Loading required package: Rcpp
R>
R> str(bdt)
Reference class 'Rcpp_date' [package ".GlobalEnv"] with 0 fields
and 42 methods, of which 31 are possibly relevant:
addDays, finalize, fromDate, getDate, getDay, getDayOfWeek, getDayOfYear,
getEndOfBizWeek, getEndOfMonth, getFirstDayOfWeekAfter,
getFirstDayOfWeekInMonth, getFirstOfNextMonth, getIMMDate, getJulian,
getLastDayOfWeekBefore, getLastDayOfWeekInMonth, getLocalClock, getModJulian,
getMonth, getNthDayOfWeek, getUTC, getWeekNumber, getYear, initialize,
setEndOfBizWeek, setEndOfMonth, setFirstOfNextMonth, setFromLocalClock,
setFromUTC, setIMMDate, subtractDays
R> bdt$fromDate( as.Date("2001-01-01") )
R> bdt$addDays( 45 )
R> print(bdt)
[1] "2001-02-15"
R>

You could also use

library(lubridate)
dmy("1/1/2001") + days(45)

In addition to the simple addition shown by others, you can also use seq.Date or seq.POSIXt to find other increments or decrements (the POSIXt version does seconds, minutes, hours, etc.):

> seq.Date( Sys.Date(), length=2, by='3 months' )[2]
[1] "2012-07-25"