Skip to content

Instantly share code, notes, and snippets.

Last active December 5, 2017 14:05
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Creating ISO 8601-extended in PHP, using DateTime. This includes milliseconds (and if you want, microseconds). Based on the work mentioned here:
// Our input
$time = microtime(true);
// Determining the microsecond fraction
$microSeconds = sprintf("%06d", ($time - floor($time)) * 1000000);
// Creating our DT object
$tz = new DateTimeZone("Etc/UTC"); // NOT using a TZ yields the same result, and is actually quite a bit faster. This serves just as an example.
$dt = new DateTime(date('Y-m-d H:i:s.'. $microSeconds, $time), $tz);
// Compiling the date. Limiting to milliseconds, without rounding
$iso8601Date = sprintf(
// Formatting according to ISO 8601-extended
/* // Proving the flip-over:
string(28) "2013-06-26T13:43:21.999+0000"
string(28) "2013-06-26T13:43:21.999+0000"
string(28) "2013-06-26T13:43:22.000+0000"
string(28) "2013-06-26T13:43:22.000+0000"
string(28) "2013-06-26T13:43:22.001+0000"
string(28) "2013-06-26T13:43:22.001+0000"
Copy link

I've developer PHP-Jiffy many months ago to solve this problem in a more general way, maybe you can enjoy it:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment