Bratt Swan Bratt Swan - 26 days ago 6x
R Question

Return error message if date format isn't correct

I have a function call specific date format in it. For example, only if format is

2002-09-04 16:45:40

Then the function will work. Otherwise, it would return an error message such as

"Format incorrect"

I am wondering how to achieve it?


Try this: <- function(d) {
  if(, '%Y-%m-%d %H:%M:%S'))) stop("Format incorrect")
  return(format(d, format='%Y-%m-%d %H:%M:%S', usetz = FALSE))
}'2002-09-04 16:45:40')
#[1] "2002-09-04 16:45:40"'09-04-2002 16:45:40')
#Error in"09-04-2002 16:45:40") : Format incorrect