Create a Vector of All Days Between Two Dates

RLubridate

R Problem Overview


Is there an easy way in R for me to itemize all valid days that occurred between two specified dates? For instance, I'd like the following inputs:

itemizeDates(startDate="12-30-11", endDate="1-4-12")

To produce the following dates:

"12-30-11" "12-31-11", "1-1-12", "1-2-12", "1-3-12", "1-4-12"

I'm flexible on classes and formatting of the dates, I just need an implementation of the concept.

R Solutions


Solution 1 - R

You're looking for seq

> seq(as.Date("2011-12-30"), as.Date("2012-01-04"), by="days")
[1] "2011-12-30" "2011-12-31" "2012-01-01" "2012-01-02" "2012-01-03"
[6] "2012-01-04"

Or, you can use :

> as.Date(as.Date("2011-12-30"):as.Date("2012-01-04"), origin="1970-01-01")
[1] "2011-12-30" "2011-12-31" "2012-01-01" "2012-01-02" "2012-01-03"
[6] "2012-01-04"

Here's a function to meet your specific request

itemizeDates <- function(startDate="12-30-11", endDate="1-4-12", 
                         format="%m-%d-%y") {
  out <- seq(as.Date(startDate, format=format), 
             as.Date(endDate, format=format), by="days")  
  format(out, format)
}

> itemizeDates(startDate="12-30-11", endDate="1-4-12")
[1] "12-30-11" "12-31-11" "01-01-12" "01-02-12" "01-03-12" "01-04-12"

Solution 2 - R

I prefer using the lubridate package to solve datetime problems. It is more intuitive and easier to understand and use once you know it.

library(lubridate)
#mdy() in lubridate package means "month-day-year", which is used to convert
#the string to date object
>start_date <- mdy("12-30-11")
>end_date <- mdy("1-4-12")
#calculate how many days in this time interval
>n_days <- interval(start_date,end_date)/days(1)
>start_date + days(0:n_days)
[1]"2011-12-30" "2011-12-31" "2012-01-01" "2012-01-02" "2012-01-03" "2012-01-04"
#convert to original format
format(start_date + days(0:n_days), format="%m-%d-%y")
[1] "12-30-11" "12-31-11" "01-01-12" "01-02-12" "01-03-12" "01-04-12"

Reference: Dates and Times Made Easy with lubridate

Solution 3 - R

2 similar implementations in lubridate:

library(lubridate)

as_date(mdy("12-30-11"):mdy("1-4-12"))

# OR

seq(mdy("12-30-11"), mdy("1-4-12"), by = "days")

These don't format your dates in month-day-year but you can fix the formatting if you want. But year-month-day is a bit easy to work with when analyzing.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeff AllenView Question on Stackoverflow
Solution 1 - RGSeeView Answer on Stackoverflow
Solution 2 - RyusuzechView Answer on Stackoverflow
Solution 3 - RJeff ParkerView Answer on Stackoverflow