Skip to content

Instantly share code, notes, and snippets.

@sloanlance
Created January 15, 2018 20:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sloanlance/69b9cf4d63192d4e00168d45e2f858d5 to your computer and use it in GitHub Desktop.
Save sloanlance/69b9cf4d63192d4e00168d45e2f858d5 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