Skip to content

Instantly share code, notes, and snippets.

@oojacoboo
Created October 13, 2012 04:10
Show Gist options
  • Save oojacoboo/3883188 to your computer and use it in GitHub Desktop.
Save oojacoboo/3883188 to your computer and use it in GitHub Desktop.
Make those dates work!
/**
* 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 $dateTime
* @return bool
*/
function isValidDateTime($dateTime) {
if(preg_match("/^(\d{4})-(\d{2})-(\d{2})( ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]))?$/", $dateTime, $matches)) {
if(checkdate($matches[2], $matches[3], $matches[1])) {
return true;
}
}
return false;
}
/**
* 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;
$isTimestamp = ((((string) (int) $dateOrTime === $dateOrTime) && ($dateOrTime <= PHP_INT_MAX) && ($dateOrTime >= ~PHP_INT_MAX))
|| (is_int($dateOrTime) && $dateOrTime <= PHP_INT_MAX && $dateOrTime >= ~PHP_INT_MAX));
//is it a normal datetime string
if(is_string($dateOrTime) && $isTimestamp === false && isValidDateTime($dateOrTime) === true) {
return date($format, strtotime($dateOrTime)); //ensure we have the correct format
//maybe it's a unix timestamp
} elseif($isTimestamp === 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;
$isTimestamp = ((((string) (int) $dateOrTime === $dateOrTime) && ($dateOrTime <= PHP_INT_MAX) && ($dateOrTime >= ~PHP_INT_MAX))
|| (is_int($dateOrTime) && $dateOrTime <= PHP_INT_MAX && $dateOrTime >= ~PHP_INT_MAX));
//maybe it's a unix timestamp
if($isTimestamp === true) {
return (int) $dateOrTime; //no need to change
//maybe it's datetime string
} elseif(is_string($dateOrTime) && $isTimestamp === 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