【问题标题】:Enter a month and get the 1st and last day for it in the particular year输入一个月并获取特定年份的第一天和最后一天
【发布时间】:2019-03-20 16:35:18
【问题描述】:

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

【问题讨论】:

    标签: r date


    【解决方案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。

    【讨论】:

      【解决方案2】:

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

      无论您输入什么格式,都要确保它始终保持一致。在这里,我认为输入始终是月份名称和完整年份。

      【讨论】:

        猜你喜欢
        • 2017-10-29
        • 1970-01-01
        • 1970-01-01
        • 2014-11-21
        • 2011-11-24
        • 1970-01-01
        • 2015-07-09
        • 2018-05-28
        • 2017-08-19
        相关资源
        最近更新 更多