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. I want output in TRUE or FALSE format, eg
Input :
date<- c('12/05/2016','35/11/2067','12/52/1000')
Output :
TRUE FALSE FALSE
You can use this function:
IsDate <- function(mydate, date.format = "%d/%m/%y") {
tryCatch(!is.na(as.Date(mydate, date.format)),
error = function(err) {FALSE})
}
IsDate(date)
[1] TRUE FALSE FALSE
Original source of the code here .
.
you can also use lubridate package:
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.