'PHP date() returning format yyyy-mm-ddThh:mm:ss.uZ

I have checked out the following question/responses: How do I get the format of “yyyy-MM-ddTHH:mm:ss.fffZ” in php? The responses include links to Microsoft documentation to format dates but these do not work in PHP.

The the top answer suggest

date('Y-m-dTH:i:s.uZ') //for the current time

This outputs 2013-03-22EDT12:56:35.000000-1440016

Background

I am working with an API which requires a timestamp in the format above. The API is based in the UK (GMT) and my server is in Australia (AEST).

The example given in the API documentation ask for the date to be in this format:

2011-07-15T16:10:45.555Z

The closest I can get to this is date('c') which outputs:

2014-07-03T16:41:59+10:00//Notice the Z is replaced with a time diff in hours

I believe the 'Z' refers to a Zone but it is not mentioned in the PHP documentation.

Unfortunatly when I post this format, the API is reading the time and taking 10 hours off. I get an error saying that the date cannot be in the past (as it is checking against the local time in Melbourne, but seeing a time 10 hours earlier).

I have tried trimming the timestamp to remove the +1000 which the API accepts, but the record is showing as created as 10 hours earlier.

I need to match the timestamp required but I cannot find any way to replicate the above output, in PHP for Melbourne, Australia. Any assistance is much appreciated.

First question on SO so please let me know how I have gone



Solution 1:[1]

The 3 number last before Z is just the 3 decimal place of time in milliseconds

The function microtime(true) gave the current time in milliseconds, would output like 1631882476.298437 In this situation it would be .298Z

Examples

  • 1652030212.6311 = .631Z
  • 1652030348.0262 = .026Z
  • 1652030378.5458 = .545Z

Codes

$milliseconds = microtime(true);
    
// Round to integer 
$timestamp = floor($milliseconds);

// Get number after dots
$uuuu = preg_replace("/\d+\./", "", "$milliseconds");

// Get last 3 number decimal place
$u = substr($uuuu, 0, 3);

// Print date by the timestamp timestamp
echo date("Y-m-d\TH:i:s", $timestamp). ".{$u}Z";

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1