Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment a date by some time period

Tags:

r

When using the "+" operator to increment a date (or date-time), how do i specify that the increment is in days (or months, or weeks, or years)?

> Sys.Date()
[1] "2013-08-23"
> Sys.Date() + 1
[1] "2013-08-24"
> ISOdate(2013,8,23)
[1] "2013-08-23 12:00:00 GMT"
> ISOdate(2013,8,23) + 1
[1] "2013-08-23 12:00:01 GMT"
like image 395
gcbenison Avatar asked Aug 23 '13 18:08

gcbenison


People also ask

How can I increment dates in SAS?

Use the INTNX function to increment dates by intervals. For example, suppose you want to know the date of the start of the week that is six weeks from the week of 17 October 1991. The function INTNX('WEEK','17OCT91'D,6) returns the SAS date value '24NOV1991'D.

How do you increment a date object?

To increment a JavaScript date object by one or more days, you can use the combination of setDate() and getDate() methods that are available for any JavaScript Date object instance. The setDate() method allows you to change the date of the date object by passing an integer representing the day of the month.


2 Answers

Use lubridate::days

> require(lubridate)
> Sys.Date()
[1] "2013-08-23"
> Sys.Date() + days(1)
[1] "2013-08-24"
> ISOdate(2013, 8, 23)
[1] "2013-08-23 12:00:00 GMT"
> ISOdate(2013, 8, 23) + days(1)
[1] "2013-08-24 12:00:00 GMT"

With lubridate, you can also use years(), seconds(), etc., or define your own duration.

like image 61
Gregor Thomas Avatar answered Oct 13 '22 12:10

Gregor Thomas


You could use seq for some basic calculations:

today = Sys.Date()
fiveWeeksAhead = tail(seq(today, by = 'week', length = 5), 1)

Or use a package like lubridate if you need more advanced functions.

like image 40
Fernando Avatar answered Oct 13 '22 14:10

Fernando