Home > Enterprise >  Convert unix time to UTC date/time in PHP
Convert unix time to UTC date/time in PHP

Time:12-12

The UTC day 2022-12-11 starts at unix time 1670716800 (which is obviously divisible by 24*3600).

In PHP, I can convert it from left to right this way:

$Date = "2022-12-11";
echo strtotime ($Date." 00:00 UTC"); 

As expected, the output is 1670716800.

But how to convert it back? If I do getdate(1670716800), I get a date with a time, but in my local time zone, whereas I want UTC.

I do not want to use object oriented PHP if this can be avoided.

CodePudding user response:

My timezone is UTC so you will get different results, but use the date_default_timezone_set() function to dafine what the date() function will do with the timestamp

$Date = "2022-12-11";
$tstamp = strtotime ($Date." 00:00:00 UTC");

echo date_default_timezone_get() . '-';
echo date('Y/m/d H:i:s', $tstamp) . PHP_EOL. PHP_EOL;


date_default_timezone_set('America/Los_Angeles');
echo date_default_timezone_get() . '-';
echo date('Y/m/d H:i:s', $tstamp) . PHP_EOL. PHP_EOL;

date_default_timezone_set('Australia/Brisbane');
echo date_default_timezone_get()  . '-';
echo date('Y/m/d H:i:s', $tstamp) . PHP_EOL;

RESULTs

UTC-2022/12/11 00:00:00

America/Los_Angeles-2022/12/10 16:00:00

Australia/Brisbane-2022/12/11 10:00:00

CodePudding user response:

$timestamp = 1607980736;
$utc_date_time = date('Y-m-d H:i:s', $timestamp);
echo $utc_date_time;

Output: 2021-12-11 16:45:36

  • Related