11

I want to get the date sequence between a startDate and endDate by adding 1 month to the startDate. ie, if startDate is 2013-01-31 and endDate is 2013-07-31, I would prefer to see dates like this:

"2013-01-31" "2013-02-28" "2013-03-31" "2013-04-30" "2013-05-31" "2013-06-30" "2013-07-31"

I have tried

seq.Date(as.Date("2013-01-31"),by="month",length.out=7)

But the output of this code is like this

> seq.Date(as.Date("2013-01-31"),by="month",length.out=7)
[1] "2013-01-31" "2013-03-03" "2013-03-31" "2013-05-01" "2013-05-31" "2013-07-01" "2013-07-31"

So, what is the simplest solution to get the correct output?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Dinoop Nair
  • 2,663
  • 6
  • 31
  • 51

2 Answers2

24

I have to work with dates in R, and one of the most useful packages that I found for date data is lubridate. For your problem, you can simply do the following:

require(lubridate)
# ymd function parses dates in year-month-day format
startDate <- ymd('2013-01-31')
# The %m+% adds months to dates without exceeding the last day
myDates <- startDate %m+% months(c(0:6))

lubridate also has many other functions for dates, and I highly recommend taking a look.

ialm
  • 8,510
  • 4
  • 36
  • 48
  • However, it doesn't work post February. `as.Date("2019-02-28") %m-% months(6)` gives me an output as `"2018-11-28"` – Bruce Wayne Apr 02 '19 at 20:16
  • @BruceWayne There are some edge cases when dealing with dates. For your example, it may be because it is not clear whether the user wants the 28th day of the month or the last day of the month. A safer approach would be to use the first day of the month and subtract a day, like in the other answers. For your example, `as.Date("2019-03-01") %m-% months(6) - days(1)` will give you `"2018-08-31"`. – ialm Apr 08 '19 at 19:24
15

This is not working, because R is not sure what to do with last day of the month. So I have a simple solution: do the same but use 1st day of the next month and then substract 1:

seq(as.Date("2013-02-1"),by="month",length.out=7) - 1
[1] "2013-01-31" "2013-02-28" "2013-03-31" "2013-04-30" "2013-05-31" "2013-06-30" "2013-07-31"
desertnaut
  • 57,590
  • 26
  • 140
  • 166
bartektartanus
  • 15,284
  • 6
  • 74
  • 102
  • bug bug.....it is not working for date="2013-01-30" > seq(as.Date("2013-01-30")+1,by="month",length.out=7)-1 [1] "2013-01-30" "2013-03-02" "2013-03-30" "2013-04-30" "2013-05-30" "2013-06-30" "2013-07-30" – Dinoop Nair Jul 17 '13 at 10:25
  • What you want to do? Get second to last day of the month? if so use seq(as.Date("2013-02-1"),by="month",length.out=7)-2 [1] "2013-01-30" "2013-02-27" "2013-03-30" "2013-04-29" "2013-05-30" "2013-06-29" "2013-07-30" – bartektartanus Jul 17 '13 at 11:15
  • yyyy/mm/dd,yyyy/mm+1/dd,yyyy/mm+2/dd....this format..if a date is invalid,then use the just previous valid date(ie,2013-02-31 should converted to 2013-02-28) – Dinoop Nair Jul 17 '13 at 11:45