Skip to content

Instantly share code, notes, and snippets.

@Zegnat
Last active December 16, 2015 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zegnat/5378588 to your computer and use it in GitHub Desktop.
Save Zegnat/5378588 to your computer and use it in GitHub Desktop.
Getting the closest midnight relative to a certain DateTime.
<?php
function closestMidnight($date) {
if (!is_a($date, 'DateTime')) {
try { $date = new DateTime($date); }
catch (Exception $e) {
if (is_numeric($date)) { $date = (new DateTime())->setTimestamp(intval($date)); }
else { return false; }
}
}
$comp = clone $date;
return $date->modify(($date>$comp->modify('noon')?'+1 day ':'').'midnight');
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment