Skip to content

Instantly share code, notes, and snippets.

@Dynom
Last active December 5, 2017 14:05
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dynom/5866837 to your computer and use it in GitHub Desktop.
Save Dynom/5866837 to your computer and use it in GitHub Desktop.
Creating ISO 8601-extended in PHP, using DateTime. This includes milliseconds (and if you want, microseconds). Based on the work mentioned here: http://stackoverflow.com/a/4414060/1061927
<?php
// 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(
"%s%03d%s",
$dt->format("Y-m-d\TH:i:s."),
floor($dt->format("u")/1000),
$dt->format("O")
);
// Formatting according to ISO 8601-extended
var_dump(
$iso8601Date
);
/* // 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"
*/
@castarco
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