【问题标题】:How to check whether entered date is in format yyyy/mm/dd?如何检查输入的日期是否为 yyyy/mm/dd 格式?
【发布时间】:2019-05-07 10:45:36
【问题描述】:

我的代码中的输入要求输入日期,我希望用户输入为 yyyy/mm/dd。输入日期后,我想检查日期是否实际上是该格式,如果不是,将要求用户再次输入日期。

我找到了一个应该在这里检查的函数:https://gist.github.com/micstr/69a64fbd0f5635094a53

但是,当我将此函数添加到我的代码并输入错误的日期格式(“2016/18/24”)时,此函数的返回不是 FALSE,而是 TRUE。

代码如下:

library(lubridate)
IsDate <- function(mydate) {
  tryCatch(!is.na(as.Date(mydate, "",tryFormats = "%Y/%m/%d")),  
           error = function(err) {FALSE})  
}

date1<- readline("Enter date (Format: yyyy/mm/dd):")

check <- IsDate(date1)
while(check == FALSE){
  otp_date <- readline("Date in wrong format. Enter again:")
  check <- IsDate(date1)
}
date1<- as.Date(date1)

我需要如何调整我的代码以解决我的问题?

【问题讨论】:

  • 嗨。您能否再解释一下,即为什么您认为您输入的格式“错误”?

标签: r date lubridate


【解决方案1】:

也许改用chron-package?


IsDate <- function(mydate) {
  tryCatch(!is.na(suppressWarnings(chron(mydate, format = "y/m/d"))),  
           error = function(err) {FALSE})  
}

> IsDate("02/02/2016")
[1] FALSE

> IsDate("2016/18/24")
[1] FALSE

> IsDate("2019/10/03")
[1] TRUE

【讨论】:

  • 好的,谢谢!当我输入错误的月份/日期时,它现在可以工作。但是,如果我输入例如02/02/2016,我会得到TRUE,尽管格式不是YYYY/MM/DD。我可以强制输入错误的日期为正确的格式或调整函数使其不首先返回TRUE吗?
  • 非常感谢您的帮助!现在完美运行!
【解决方案2】:

不要使用正则表达式。使用日期库。我最喜欢的一个无需格式字符串即可解析日期(和日期时间):

R> library(anytime)
R> anydate("2016/18/24")
[1] NA
R> anydate("2016/08/24")
[1] "2016-08-24"
R> 

所以,如果你得到一个约会回来,一切都很好。如果您收到NA,则表示有问题。

【讨论】:

    【解决方案3】:

    这是一个矢量化的基本 R 函数,可与 NA 一起使用,并且可以安全地防止 SQL 注入:

    is_date = function(x, format = NULL) {
      formatted = try(as.Date(x, format), silent = TRUE)
      is_date = as.character(formatted) == x & !is.na(formatted)  # valid and identical to input
      is_date[is.na(x)] = NA  # Insert NA for NA in x
      return(is_date)
    }
    

    我们试试吧:

    > is_date(c("2020-08-11", "2020-13-32", "2020-08-11; DROP * FROM table", NA), format = "%Y-%m-%d")
    ## TRUE FALSE FALSE    NA
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多