且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从/向日期减去/添加天数?

更新时间:2023-11-29 13:12:04

只需减去一个数字:

> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"

由于 Date 类只有几天,您可以对其进行基本的算术运算.

Since the Date class only has days, you can just do basic arithmetic on it.

如果您出于某种原因想使用 POSIXlt,那么您可以使用它的插槽:

If you want to use POSIXlt for some reason, then you can use it's slots:

> a <- as.POSIXlt("2009-10-04")
> names(unclass(as.POSIXlt("2009-10-04")))
[1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"
> a$mday <- a$mday - 6
> a
[1] "2009-09-28 EDT"