How to validate date in R
r
Solution
Simple way:
d <- try(as.Date(date, format="%d-%m-%Y %H:%M:%S"))
if("try-error" %in% class(d) || is.na(d)) {
print("That wasn't correct!")
}
Explanation: `format.Date` uses `as.Date` internally to convert `date` into an object of the `Date` class. However, it does not use a format option, so `as.Date` uses the default format, which is `%Y-%m-%d`and then `%Y/%m/%d`.
The `format` option from `format.Date` is used only for the output, not for the parsing. Quoting from the `as.Date` man page:
The ‘as.Date’ methods accept character strings, factors, logical ‘NA’ and objects of classes ‘"POSIXlt"’ and ‘"POSIXct"’. (The last is converted to days by ignoring the time after midnight in the representation of the time in specified timezone, default UTC.) Also objects of class ‘"date"’ (from package ‘date’) and ‘"dates"’ (from package ‘chron’). Character strings are processed as far as necessary for the format specified: any trailing characters are ignored.
However, when you directly call `as.Date` with a format specification, nothing else will be allowed than what fits your format.
See also: `?as.Date`
Problem
I have a date in the format `dd-mm-yyyy HH:mm:ss` What is the best and easiest way to validate this date? I tried ``` d <- format.Date(date, format="%d-%m-%Y %H:%M:%S") ``` But how can I catch the error when an illegal date is passed?