Skip to content

Instantly share code, notes, and snippets.

@oojacoboo
Created October 11, 2012 01:24
Show Gist options
  • Save oojacoboo/3869584 to your computer and use it in GitHub Desktop.
Save oojacoboo/3869584 to your computer and use it in GitHub Desktop.
/**
* Ensures that the value passed is in datetime format
* @param null $dateOrTime
* @param string $format
* @return null|string
*/
function ensureDateTime($dateOrTime = null, $format = "c") {
if(!$dateOrTime)
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 null;
}
}
/**
* Ensures that the passed value is a valid unix timestamp
* @param null $dateOrTime
* @return int|null
*/
function ensureTimestamp($dateOrTime = null) {
if(!$dateOrTime)
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 null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment