Check whether the string is a unix timestamp Check whether the string is a unix timestamp php php

Check whether the string is a unix timestamp


Ok, after fiddling with this for some time, I withdraw the solution with date('U') and suggest to use this one instead:

function isValidTimeStamp($timestamp){    return ((string) (int) $timestamp === $timestamp)         && ($timestamp <= PHP_INT_MAX)        && ($timestamp >= ~PHP_INT_MAX);}

This check will only return true if the given $timestamp is a string and consists solely of digits and an optional minus character. The number also has to be within the bit range of an integer (EDIT: actually unneeded as shown here).

var_dump( isValidTimeStamp(1)             ); // falsevar_dump( isValidTimeStamp('1')           ); // TRUEvar_dump( isValidTimeStamp('1.0')         ); // falsevar_dump( isValidTimeStamp('1.1')         ); // falsevar_dump( isValidTimeStamp('0xFF')        ); // falsevar_dump( isValidTimeStamp('0123')        ); // falsevar_dump( isValidTimeStamp('01090')       ); // falsevar_dump( isValidTimeStamp('-1000000')    ); // TRUEvar_dump( isValidTimeStamp('+1000000')    ); // falsevar_dump( isValidTimeStamp('2147483648')  ); // falsevar_dump( isValidTimeStamp('-2147483649') ); // false

The check for PHP_INT_MAX is to ensure that your string can be used correctly by date and the likes, e.g. it ensures this doesn't happen*:

echo date('Y-m-d', '2147483648');  // 1901-12-13echo date('Y-m-d', '-2147483649'); // 2038-01-19

On 64bit systems the integer is of course larger than that and the function will no longer return false for "2147483648" and "-2147483649" but for the corresponding larger numbers.


(*) Note: I'm not 100% sure, the bit range corresponds with what date can use though


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 )


I came across the same question and created the following solution for my self, where I don't have to mess with regular expressions or messy if-clauses:

/** * @param string $string * @return bool */public function isTimestamp($string){    try {        new DateTime('@' . $string);    } catch(Exception $e) {        return false;    }    return true;}