输入一个月并获取特定年份的第一天和最后一天

时间:2018-10-16 07:50:54

标签: r date

R中是否有一种方法可以获取指定月份的第一天和最后一天。 例如。

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

2 个答案:

答案 0 :(得分:1)

使用lubridate库:

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

对于基本的R解决方案,我们可以定义一个辅助方法来增加月份。然后,可以通过将一个月的第一个月加上一个月并减去一天来计算给定月份的最后一天:

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

add.months辅助功能的信用额授予this SO question

答案 1 :(得分:1)

我们可以在基础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"

无论输入哪种格式,请确保其前后一致。在这里,我考虑到输入始终是月份名称和完整年份。