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
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
<?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" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've developer PHP-Jiffy many months ago to solve this problem in a more general way, maybe you can enjoy it: