[英]R - Date format check
I am trying to check whether a given date is in dd/mm/yyyy format or not in R
language and also whether it is a valid date or not at the same time.我正在尝试检查给定日期是否为
R
语言中的 dd/mm/yyyy 格式,以及它是否同时为有效日期。 I want output in TRUE or FALSE format, eg我想要 TRUE 或 FALSE 格式的输出,例如
Input :输入:
date<- c('12/05/2016','35/11/2067','12/52/1000')
Output :输出:
TRUE FALSE FALSE
you can also use lubridate package:您还可以使用 lubridate 包:
library(lubridate)
!is.na(parse_date_time(c('12/05/2016','35/11/2067','12/52/1000'),orders="dmy"))
Here is a vectorized base R function that handles NA
, and is safe against SQL injection:这是一个处理
NA
的矢量化基本 R 函数,并且可以安全地防止 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)
}
Let's try:让我们试试:
> is_date(c("2020-08-11", "2020-13-32", "2020-08-11; DROP * FROM table", NA), format = "%Y-%m-%d")
## TRUE FALSE FALSE NA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.