如何检查输入的日期是否为yyyy/mm/dd格式?
How to check whether entered date is in format yyyy/mm/dd?
我的代码中的输入要求输入日期,我希望用户输入 yyyy/mm/dd。输入日期后,我想检查日期是否确实采用该格式,如果不是,将要求用户再次输入日期。
我发现了一个应该在这里检查的函数:https://gist.github.com/micstr/69a64fbd0f5635094a53
但是,当我将此函数添加到我的代码并输入错误的日期格式(“2016/18/24”)时,此函数的 return 不是 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)
我需要如何调整我的代码才能解决我的问题?
也许改用 chron
-包?
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
不要使用正则表达式。使用日期库。我最喜欢的一个解析日期(和日期时间)而不需要格式字符串:
R> library(anytime)
R> anydate("2016/18/24")
[1] NA
R> anydate("2016/08/24")
[1] "2016-08-24"
R>
所以如果你得到一个日期,一切都很好。如果您收到 NA
,则说明存在问题。
这是一个矢量化的基础 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
我的代码中的输入要求输入日期,我希望用户输入 yyyy/mm/dd。输入日期后,我想检查日期是否确实采用该格式,如果不是,将要求用户再次输入日期。
我发现了一个应该在这里检查的函数:https://gist.github.com/micstr/69a64fbd0f5635094a53
但是,当我将此函数添加到我的代码并输入错误的日期格式(“2016/18/24”)时,此函数的 return 不是 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)
我需要如何调整我的代码才能解决我的问题?
也许改用 chron
-包?
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
不要使用正则表达式。使用日期库。我最喜欢的一个解析日期(和日期时间)而不需要格式字符串:
R> library(anytime)
R> anydate("2016/18/24")
[1] NA
R> anydate("2016/08/24")
[1] "2016-08-24"
R>
所以如果你得到一个日期,一切都很好。如果您收到 NA
,则说明存在问题。
这是一个矢量化的基础 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