Check whether the string is a unix timestamp

PhpDatetimeTimeUnix Timestamp

Php Problem Overview


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 http://www.sitepoint.com/forums/showthread.php?t=585963">this thread via Google, but it doesn't come up with a very solid answer, I'm afraid. (And yes, I cribbed the question from the original poster on the aforementioned thread).

Php Solutions


Solution 1 - Php

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)             ); // false
var_dump( isValidTimeStamp('1')           ); // TRUE
var_dump( isValidTimeStamp('1.0')         ); // false
var_dump( isValidTimeStamp('1.1')         ); // false
var_dump( isValidTimeStamp('0xFF')        ); // false
var_dump( isValidTimeStamp('0123')        ); // false
var_dump( isValidTimeStamp('01090')       ); // false
var_dump( isValidTimeStamp('-1000000')    ); // TRUE
var_dump( isValidTimeStamp('+1000000')    ); // false
var_dump( isValidTimeStamp('2147483648')  ); // false
var_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-13
echo 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

Solution 2 - Php

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 )

Solution 3 - Php

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;
}

Solution 4 - Php

this looks like the way to go:

function is_timestamp($timestamp) {
    if(strtotime(date('d-m-Y H:i:s',$timestamp)) === (int)$timestamp) {
        return $timestamp;
    } else return false;
}

you could also add a is_numeric() check and all sort of other checks.
but this should/could be the basics.

Solution 5 - Php

Improved answer to @TD_Nijboer.

This will avoid an exception be thrown if the supplied string is not a time stamp:

function isTimestamp($timestamp) {
    if(ctype_digit($timestamp) && strtotime(date('Y-m-d H:i:s',$timestamp)) === (int)$timestamp) {
    	return true;
    } else {
    	return false;
    }
}

Solution 6 - Php

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;

Solution 7 - Php

or

if ($startDate < strtotime('-30 years') || $startDate > strtotime('+30 years')) {
    //throw exception
}

Solution 8 - Php

You want to check if a string contains a high number?

is_numeric() is the key

Or convert it to DateTime and do some checks with it like an expected date range.

Solution 9 - Php

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.

Solution 10 - Php

Another possibility:

$date_arg = time();
$date_is_ok = ($date_arg === strtotime(date('c', $date_arg)));

Solution 11 - Php

    //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;
		}
	}

Solution 12 - Php

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));
}

Solution 13 - Php

I do two checks from timestamp, both utc and usually higher than 11/13 digit and after control

// Is Timestamp control function
function isTimestamp($x,$lenMax = 11,$compare = 30){
if (!ctype_digit($x)) return false;
$x = strlen($x) >= $lenMax ? $x / 1000 : $x;
if ($x < strtotime("-{$compare} years") || $x > strtotime("+{$compare} years")) {	
	return false;
}
return true;

}

// Timestamp UTC usually take from javascript -> Date.Now() -> 1618362206593
echo check_timestamp(1618362206593); // Return -> true
// or that stand time()
echo check_timestamp(1618359229); // return -> true
// UTC
echo check_timestamp(5618362206593); // Return -> false
// or that stand time()
echo check_timestamp(5618359229); // return -> false

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRHPTView Question on Stackoverflow
Solution 1 - PhpGordonView Answer on Stackoverflow
Solution 2 - PhpYacobyView Answer on Stackoverflow
Solution 3 - PhpsimplychrislikeView Answer on Stackoverflow
Solution 4 - PhpTD_NijboerView Answer on Stackoverflow
Solution 5 - PhpDimitar DarazhanskiView Answer on Stackoverflow
Solution 6 - PhpgoatView Answer on Stackoverflow
Solution 7 - Phpalex toaderView Answer on Stackoverflow
Solution 8 - PhpPatrick CornelissenView Answer on Stackoverflow
Solution 9 - PhpAlex MatiushkinView Answer on Stackoverflow
Solution 10 - PhpChrisView Answer on Stackoverflow
Solution 11 - Phpalex toaderView Answer on Stackoverflow
Solution 12 - PhpMTsetView Answer on Stackoverflow
Solution 13 - PhpClaryView Answer on Stackoverflow