Skip to content

Instantly share code, notes, and snippets.

@oojacoboo
Created October 13, 2012 04:14
Show Gist options
  • Save oojacoboo/3883191 to your computer and use it in GitHub Desktop.
Save oojacoboo/3883191 to your computer and use it in GitHub Desktop.
Ensure those dates and times are working for you!
/**
* Checks a date/time string to verify it's a valid date/time
* Supports both Y-m-d and Y-m-d H:i:s
* @param $dateOrTime
* @return bool
*/
function isValidDateTime($dateOrTime) {
if(preg_match("/^(\d{4})-(\d{2})-(\d{2})( ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]))?$/", $dateOrTime, $matches)) {
if(checkdate($matches[2], $matches[3], $matches[1])) {
return true;
}
}
return false;
}
/**
* Checks a timestamp to make sure it's valid, integer or string format supported
* @param $dateOrTime
* @return bool
*/
function isValidTimestamp($dateOrTime) {
return ((((string) (int) $dateOrTime === $dateOrTime) && ($dateOrTime <= PHP_INT_MAX) && ($dateOrTime >= ~PHP_INT_MAX))
|| (is_int($dateOrTime) && $dateOrTime <= PHP_INT_MAX && $dateOrTime >= ~PHP_INT_MAX));
}
/**
* Ensures that the value passed is in datetime format
* @param null $dateOrTime
* @param string $format
* @param string $fallback
* @return null|string
*/
function ensureDateTime($dateOrTime = null, $format = "c", $fallback = null) {
if(!$dateOrTime && !$fallback)
return null;
//is it a normal datetime string
if(is_string($dateOrTime) && isValidTimestamp($dateOrTime) === false && isValidDateTime($dateOrTime) === true) {
return date($format, strtotime($dateOrTime)); //ensure we have the correct format
//maybe it's a unix timestamp
} elseif(isValidTimestamp($dateOrTime) === true) {
return date($format, $dateOrTime);
//rely on the set fallback if set
} elseif($fallback !== null) {
return date($format, strtotime($fallback));
//no idea, return itself
} else {
return $dateOrTime;
}
}
/**
* Ensures that the passed value is a valid unix timestamp
* @param null $dateOrTime
* @param int $fallback
* @return int|null
*/
function ensureTimestamp($dateOrTime = null, $fallback = null) {
if(!$dateOrTime && !$fallback)
return null;
//maybe it's a unix timestamp
if(isValidTimestamp($dateOrTime) === true) {
return (int) $dateOrTime; //no need to change
//maybe it's datetime string
} elseif(is_string($dateOrTime) && isValidTimestamp($dateOrTime) === false && isValidDateTime($dateOrTime) === true) {
return strtotime($dateOrTime);
//rely on the set fallback if set
} elseif($fallback !== null) {
return (int) $fallback;
//no idea
} else {
return $dateOrTime;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment