Home > Net >  PHP: How can one find the time difference in seconds between values "2022-06-24T15:04:37.000000
PHP: How can one find the time difference in seconds between values "2022-06-24T15:04:37.000000

Time:06-25

I am using an API that is giving me two time values to describe its execution, but in different formats. For instance:

'created_at' => '2022-06-24T15:04:37.000000Z',
'processed_at' => '2022-06-24 15:05:15',

I am running the code:

$created = "2022-06-24T15:04:37.000000Z";
$processed = "2022-06-24 15:05:15";
$createdtime = strtotime($created);
$processedtime = strtotime($processed);
$diff = $processedtime - $createdtime;
echo "Created: $created Processed: $processed createdtime: $createdtime processedtime: $processedtime Diff: $diff<br/>\n";

On two different servers, to test how to find the difference in seconds between these two times. One on server it gives me the results:

Created: 2022-06-24T15:04:37.000000Z Processed: 2022-06-24 15:05:15 createdtime: 1656083077 processedtime: 1656083115 Diff: 38

On another server, it says:

Created: 2022-06-24T15:04:37.000000Z Processed: 2022-06-24 15:05:15 createdtime: 1656083077 processedtime: 1656097515 Diff: 14438

I am assuming that this is a timezone issue. 14400 seconds=10 hours. The "real" answer should be 38, as that's how long the API took in real life to process the request. Is there any code I could use to get a consistent result of 38 seconds across the two servers?

CodePudding user response:

processed_at doesn't contain a timezone, so PHP is using whatever it has configured as default. It looks like the timezone of processed_at is supposed to be UTC, so I'd just force it. You could just add a Z to the end of the string:

$processedtime = strtotime($processed . ' Z');

Or, more correctly, tell PHP to use UTC when no timezone is otherwise available in the string:

$processedtime = (new DateTime($processed, new DateTimeZone('UTC')))->format('U');
  • Related