Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lsloan/ace19b61ae4e16fb0583bbf5f5f67d36 to your computer and use it in GitHub Desktop.
Save lsloan/ace19b61ae4e16fb0583bbf5f5f67d36 to your computer and use it in GitHub Desktop.
PHP: A replacement for the shamefully broken DateTime::getTimestamp
/**
* Problem: `DateTime::getTimestamp` returns **_`int`_**! Calculations such as the following
* are incorrect if the `DateTime` object includes fractions of seconds:
*
* ```php
* $durationSeconds = strval($endTime->getTimestamp() - $startTimestamp);
* ```
*
* `DateTime::diff` can subtract properly, but only under PHP 7.1. (Curiously,
* `DateTime::getTimestamp` still returns `int` under PHP 7.1!)
*
* @param DateTime $aDateTime
* @return float
*/
function getTimestampWithFraction(DateTime $aDateTime) {
// One or both `floatval` calls may be unnecessary, but it's better to be safe.
return floatval($aDateTime->getTimestamp()) + floatval($aDateTime->format('.u'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment