0

Is there a way in R to get the 1st and the last day for a specified month. Eg.

Input: September 2018 or any other format to specify month and year
Expected output:
1st day function (Input) -> 01-Sep-2018 or any other valid date format
Last day function (Input) -> 30-Sep-2018 or any other valid date format
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
eclairs
  • 1,515
  • 6
  • 21
  • 26

2 Answers2

1

Using the lubridate library:

require(lubridate)
d <- as.Date('2018-09-01')
last_day <- d
day(last_day) <- days_in_month(last_day)

For a base R solution, we can define a helper method to add months. Then, the last day of a given month can be computed by adding one month to the first of the month and subtracting one day:

add.months <- function(date, n) seq(date, by=paste (n, "months"), length=2 [2]
d <- as.Date('2018-09-01')         # first of the month
last_day <- add.months(d, 1) - 1   # last of the month

Credit for the add.months helper function is given to this SO question.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

We can create a function in base R

get_first_and_last_date <- function(month_year) {
   start_date = as.Date(paste0("01 ", month_year), "%d %b %Y")
   end_date = (seq(start_date, length.out = 2, by = "month") - 1)[2]
   c(start_date, end_date)
}

get_first_and_last_date('Dec 2018')
#[1] "2018-12-01" "2018-12-31"

get_first_and_last_date('Sep 2016')
#[1] "2016-09-01" "2016-09-30"

Whatever format you enter make sure it is consistent throughout. Here I have considered the input would always be a month name and complete year.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213