Convert PHP Mongo UTC Date From Milliseconds To Date for TimeZone

Viewed 26

I have a date in UTC / Epoch format from a mongo database (1659052800000) and I'm trying to convert it to a friendly format using PHP for the PST timezone.

Here's what I've tried.

date_default_timezone_set('PST');

$this->vars[dateOfEvent] = date('Y-m-d', 1659052800000);

and

date_default_timezone_set('PST');
                                            
$dt = new DateTime(1659052800000);
$this->vars[dateOfEvent] = $dt->format('Y-m-d');

but neither give me the correct date. I'm expecting it to out "2022-07-28"

1 Answers

You can set the timezone temporarily for the DateTime object. Also you need to set timestamp divided by 1000 or remove the last three zeroes.

$dt = new DateTime();
$dt->setTimestamp(1659052800000 / 1000);
$dt->setTimezone(new DateTimeZone('PST'));
echo $dt->format('Y-m-d');

prints

2022-07-28
Related