Skip to content

Instantly share code, notes, and snippets.

@lsloan
Last active January 17, 2023 07:40
Show Gist options
  • Save lsloan/56e2e39d0b0c54aecbcf84be255972c2 to your computer and use it in GitHub Desktop.
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.
/*
* 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