Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is string valid for use with strtotime()?

PHP has strtotime() which assumes the input given is a string that represents a valid time. Before using strtotime(), how can I verify that the string about to be given to it is in one of its valid formats?

like image 496
zmol Avatar asked Feb 11 '11 09:02

zmol


2 Answers

strtotime() returns false if it can't understand your date format, so you can check its return value. The function doesn't have any side effects, so trying to call it won't hurt.

// $format = ...

if (($timestamp = strtotime($format)) !== false) {
    // Obtained a valid $timestamp; $format is valid
} else {
    // $format is invalid
}

Be warned, however, that strtotime() only supports the same range of Unix timestamps as the server architecture does. This means it will incorrectly return false for certain date ranges. From the manual:

Note:

The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.

For 64-bit versions of PHP, the valid range of a timestamp is effectively infinite, as 64 bits can represent approximately 293 billion years in either direction.

Because server architectures can vary, you may be limited to 32-bit Unix timestamps depending on your use case, even though 64-bit timestamps cover a practically infinite period of time.

like image 177
BoltClock Avatar answered Oct 21 '22 07:10

BoltClock


Actually you can't check that before executing the function, but you could take a look at the official php.net page. The only thing you can do is checking whether your function returns "false".

Here's a link strtotime().

There are a lot of examples of what you can do with strtotime().

like image 44
oopbase Avatar answered Oct 21 '22 09:10

oopbase