Created
October 13, 2012 00:23
-
-
Save oojacoboo/3882526 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) && strtotime($dateOrTime) !== false) { | |
return date($format, strtotime($dateOrTime)); //ensure we have the correct format | |
//maybe it's a unix timestamp | |
} elseif(is_int($dateOrTime) && ($dateOrTime <= PHP_INT_MAX && $dateOrTime >= ~PHP_INT_MAX)) { | |
return date($format, $dateOrTime); | |
//or possibly a unix timestamp as a string | |
} elseif(is_string($dateOrTime) && strtotime($dateOrTime) === false) { | |
$dateOrTime = (int) $dateOrTime; | |
return (date($format, $dateOrTime) !== false) ? date($format, $dateOrTime) : null; | |
//no idea | |
} else { | |
return date($format, strtotime($fallback)); | |
} | |
} | |
/** | |
* 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(is_int($dateOrTime) && ($dateOrTime <= PHP_INT_MAX && $dateOrTime >= ~PHP_INT_MAX)) { | |
return $dateOrTime; //no need to change | |
//maybe it's datetime string | |
} elseif(is_string($dateOrTime) && strtotime($dateOrTime) !== false) { | |
return strtotime($dateOrTime); | |
//or possibly a unix timestamp as a string | |
} elseif(is_string($dateOrTime) && strtotime($dateOrTime) === false) { | |
return (int) $dateOrTime; | |
//no idea | |
} else { | |
return $fallback; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment