如何使用 lubridate 解析无效日期?

How to parse an invalid date with lubridate?

我需要解析日期并遇到类似“31/02/2018”的情况:

library(lubridate)
> dmy("31/02/2018", quiet = T)
[1] NA

这是有道理的,因为 2 月 31 日不存在。有没有办法将字符串“31/02/2018”解析为例如2018-02-28 ?所以不是获得 NA,而是实际约会?

谢谢。

我们可以编写一个函数,假设您的日期可能早于实际日期并且始终具有相同的格式。

library(lubridate)

get_correct_date <- function(example_date) {
  #Split vector on "/" and get 3 components (date, month, year)
  vecs <- as.numeric(strsplit(example_date, "\/")[[1]])

  #Check number of days in that month
  last_day_of_month <-  days_in_month(vecs[2])

  #If the input date is higher than actual number of days in that month
  #replace it with last day of that month
  if (vecs[1] > last_day_of_month)
    vecs[1] <- last_day_of_month

  #Paste the date components together to get new modified date
  dmy(paste0(vecs, collapse = "/"))
}


get_correct_date("31/02/2018")
#[1] "2018-02-28"

get_correct_date("31/04/2018")
#[1] "2018-04-30"

get_correct_date("31/05/2018")
#[1] "2018-05-31"

稍作修改,如果日期格式不同,或者即使某些日期小于第一个日期,您也可以调整日期。