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?
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.