I have dates that are in the following format 2016-10-16T22:12:45.104Z the dates are then converted to a datetime object by an api SDK I am using.
What I am trying to do is get the datetime object as a string exactly as '2016-10-16T22:12:45.104Z' it has to be exact and a string so I can pass it to another function.
I found the below php script on another answer here however this is for the current time.
I have tried things such as ->format('U') but nothing works, I need to get the datetime object in the same format as microtime(true) I think.
How can I use the below php code on the dates I have so that they can be echoed out exactly like '2016-10-16T22:12:45.104Z' ?
<?php
$time = microtime(true);
$tMicro = sprintf("%03d",($time - floor($time)) * 1000);
$tUtc = gmdate('Y-m-d\TH:i:s.', $time).$tMicro.'Z';
echo $tUtc;
?>
As you found in the docs 'u' is very helpful in this case. http://php.net/manual/en/class.datetime.php#118608
You should be able to use this solution "Y-m-d\TH:i:s.u\Z", but unfortunately you want milliseconds instead of microseconds and you end up with 3 extra 0s. To fix this, just divide the result of 'u' by 1000.
$dt = new DateTime('2016-10-16T22:12:45.104Z');
$helper = $dt->format('u'); //this is factor of 1000 off
$helper /= 1000
$ans = $dt->format('Y-m-d\TH:i:s'); //get the first part of what you
$ans .= "." . $helper . "Z"; //add the milliseconds back on, and Z for good measure
echo $ans . "\n";