R: How can I check the format of a timestamp?

Viewed 1880

Simple enough question but cannot find an answer. If I have some dummy timestamp:

foo <- strftime(Sys.time(), "%Y-%m-%dT%H:%M:%SZ")

With format:

"%Y-%m-%dT%H:%M:%SZ". 

How would I check what format foo is? I need to check that a user has submitted a timestamp in the correct format and would therefore need something like

if (func_bar(foo) != "%Y-%m-%dT%H:%M:%SZ") {stop("Complain")}

Is there a intrinsic R function for this?

UPDATE: (For clarity) I understand that I could change the format automatically for the user, i.e just convert which ever date is submitted. But in this particular case I want to catch it. For example I could use:

foo1 <- as.POSIXlt(Sys.time(), "UTC", "%Y-%m-%dT%H:%M:%S")

foo <- strftime(foo1, "%Y-%m-%dT%H:%M:%SZ")

To get it into the correct format.

2 Answers

Sys.time() outputs the current time as POSIXct by default. Your user would submit a character time I am assuming. If you try to convert it to POSIXct, it will become NA unless it has the exact format you specified. So, something like this will work:

if (is.na(as.POSIXct('2017-01-01 05:00:00', format = "%Y-%m-%dT%H:%M:%SZ"))) {

  stop('Date not in the right format')

}
#Error: Date not in the right format

I do not know any such function. Here is what I will do:

curr.time <- strftime(Sys.time(), "%Y-%m-%d")
if(!grepl('\\d{4}-\\d{2}-\\d{2}', as.character(curr.time))) {stop("Complain")}
Related