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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With