Skip to content

Instantly share code, notes, and snippets.

@4cm
Created July 6, 2019 10:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 4cm/4e2d5dea94f37d271fc58a77176ddffd to your computer and use it in GitHub Desktop.
Save 4cm/4e2d5dea94f37d271fc58a77176ddffd to your computer and use it in GitHub Desktop.
Validate if a Unix timestamp is valid.
/**
* Validate if a Unix timestamp is valid.
*
* @param $unixtimestamp
* @return bool
*/
function datetime_IsUnixTimeStampValid($unixtimestamp) {
//
//
///////////////////////////////////////////////////////////////////////
// Validate Date is between start and end of 32-bit Unix timestamps
// ref: https://stackoverflow.com/a/4684066/797620
///////////////////////////////////////////////////////////////////////
//
if ( !filter_var($unixtimestamp, FILTER_VALIDATE_INT, ['options' => ['min_range' => (int)0, 'max_range' => (int)2147483647]]) ) {
//
return false;
//
}
//
//
///////////////////////////////////////////////////////////////////////
// Validate
// ref: https://stackoverflow.com/a/2524761/797620
///////////////////////////////////////////////////////////////////////
//
return ((string) (int) $unixtimestamp === $unixtimestamp) && ($unixtimestamp <= PHP_INT_MAX)&& ($unixtimestamp >= ~PHP_INT_MAX);
//
}
@bmg1
Copy link

bmg1 commented Jul 8, 2021

Cool!

@duartebriz
Copy link

What about dates before 1970?

Shouldn't the 'min_range' start with a negative number.

For example the date '1901-01-01' has this timestamp: -2177391172.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment