Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP convert mktime result to UTC

I am using this code to generate yesterday's beginning of day in PST (aka America/Los_Angeles) time. I can't figure out how to convert the result to UTC.

date_default_timezone_set("America/Los_Angeles");
$time1 = date("Y-m-d H:i:s", mktime(0,0,0, date('n'), date('j')-1, date('Y')));

I tried this, but $time1 is not datetime, it's string. So the following won't work.

$time1->setTimezone(new DateTimeZone("UTC")); 
like image 674
apadana Avatar asked Aug 16 '16 23:08

apadana


1 Answers

The DateTime class can do all that for you

$date = new DateTime(null, new DateTimeZone('America/Los_Angeles')); // will use now

echo $date->format('d/m/Y H:i:s');   //16/08/2016 16:13:29

$date->setTime(0,0,0);  
$date->modify('-1 day');
echo $date->format('d/m/Y H:i:s');   // 15/08/2016 00:00:00

$date->setTimezone(new DateTimeZone('UTC'));
echo $date->format('d/m/Y H:i:s');    // 15/08/2016 07:00:00
like image 153
RiggsFolly Avatar answered Nov 09 '22 03:11

RiggsFolly