0

I'm wondering how to achieve this date format "2016-04-19T03:17:38.184+00:00" in php?

It's kinda different from ISO 8601. Please advise.

http://php.net/manual/en/function.date.php

Thanks.

Cris
  • 437
  • 2
  • 5
  • 15
  • 1
    If you don't need the milliseconds, it's just `date('c');`. If you do, see http://stackoverflow.com/questions/17909871/getting-date-format-m-d-y-his-u-from-milliseconds for some similar examples. – Mike May 23 '16 at 03:18

1 Answers1

1

It is impossible to use date() to show the milliseconds part because, from the manual:

date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

So the only way is to use DateTime and pass the microseconds to the constructor. However since we only need milliseconds, we can just round it and then remove the trailing three 0's from the end later.

$t = microtime(true);
$milli = sprintf("%03d",($t - floor($t)) * 1000);
$d = new DateTime( date('Y-m-d H:i:s.'.$milli, $t) );

echo $d->format("Y-m-d\TH:i:s.");
echo substr($d->format("u"), 0, -3);
echo $d->format('P');

Outputs:

2016-05-22T22:41:57.294-05:00

Mike
  • 23,542
  • 14
  • 76
  • 87