Last active
January 17, 2023 07:40
-
-
Save lsloan/56e2e39d0b0c54aecbcf84be255972c2 to your computer and use it in GitHub Desktop.
Get PHP DateTime objects with fractional seconds and format them according to ISO 8601.
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
/* | |
* The `DateTime` constructor doesn't create objects with fractional seconds. | |
* However, the static method `DateTime::createFromFormat()` does include the | |
* fractional seconds in the object. Finally, since ISO 8601 specifies only | |
* millisecond precision, remove the last three decimal places from the timestamp. | |
*/ | |
// DateTime object with microseconds | |
$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', '')); | |
// Truncate to milliseconds | |
$nowFormatted = substr($now->format('Y-m-d\TH:i:s.u'), 0, -3) . 'Z'; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment