Bratt Swan
Bratt Swan

Reputation: 1146

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?

Upvotes: 3

Views: 257

Answers (2)

Sandipan Dey
Sandipan Dey

Reputation: 23109

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

Upvotes: 5

Ronak Shah
Ronak Shah

Reputation: 389175

Well, you can write a function to check the format of the date input you are sending using as.Date function specifying the format argument

checkDateFormat <- function(input) {
  x <- as.Date(input, format= "%Y-%m-%d %H:%M:%S" )
  if(is.na(x))
     "Format incorrect"
  else
     "Format correct"
}

checkDateFormat("2002-09-04 16:45:40")
#[1] "Format correct"

checkDateFormat("2002-09-04")
#[1] "Format incorrect"

checkDateFormat("2002-09-04 16:45")
#[1] "Format incorrect"

Upvotes: 1

Related Questions