Created
January 15, 2018 20:30
-
-
Save sloanlance/69b9cf4d63192d4e00168d45e2f858d5 to your computer and use it in GitHub Desktop.
PHP: A replacement for the shamefully broken DateTime::getTimestamp
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
/** | |
* 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