Bratt Swan Bratt Swan - 2 months ago 8
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?

Answer

Try this:

convert.to.date <- function(d) {
  if(is.na(strptime(d, '%Y-%m-%d %H:%M:%S'))) stop("Format incorrect")
  return(format(d, format='%Y-%m-%d %H:%M:%S', usetz = FALSE))
}

convert.to.date('2002-09-04 16:45:40')
#[1] "2002-09-04 16:45:40"
convert.to.date('09-04-2002 16:45:40')
#Error in convert.to.date("09-04-2002 16:45:40") : Format incorrect