I have a string and I need to find out whether it is a unix timestamp or not, how can I do that effectively?
I found this thread via Google, but it doesn\'t come up
As a unix timestamp is a integer, use is_int(). However as is_int
() doesn't work on strings, we check if it is numeric and its intergal form is the same as its orignal form. Example:
( is_numeric($stamp) && (int)$stamp == $stamp )
//if anything else than digits inside the string then your string is no timestamp
//in which case maybe try to get the timestamp with strtotime
if(preg_match('/[^\d]/', $str)) {
$str = strtotime($str);
if (false === $str) {
//conversion failed - invalid time - invalid row
return;
}
}
If you might think to replace this solution with is_numeric(), please consider that php native function provides false positives for input strings like "1.1", "0123", "0xFF" which are not in timestamp format.
In PHP for checking if a timestamp represents a valid Gregorian date this worked for me:
function checkdateTimestamp($timestamp) {
return checkdate((int)date('m',$timestamp),(int)date('d',$timestamp),(int)date('Y',$timestamp));
}
This doesn't account for negative times(before 1970), nor does it account for extended ranges(you can use 64 bit integers so that a timestamp can represent a value far after 2038)
$valid = ctype_digit($str) && $str <= 2147483647;
or
if ($startDate < strtotime('-30 years') || $startDate > strtotime('+30 years')) {
//throw exception
}