How to Parse Dates With Different Timezones in PHP (and convert them)

Recently I was tasked with processing some content from an API, the published dates and times were coming through with timezone values in the string. My dates looked like this: 2021-09-29T04:24:39Z

If you parse these using strtotime like I was and importing them into WordPress, even if your server timezone is configured correctly, the timezone will be wrong. In my situation, the dates and times were showing all hours of the morning.

This is where the DateTime object comes in very handy. We create a new DateTime object using the provided value that we want to convert into our timezone.

I then call the setTimeZone function on the DateTime object to convert my date object into the timezone for Sydney, Australia.

Finally, we call the format function to get the date in our desired format.

$post\_date = new DateTime($published);
$post\_date->setTimeZone(new DateTimeZone('Australia/Sydney'));
$post\_date = $post\_date->format("Y-m-d H:i:s");

It’s a remarkably simple and powerful way to convert date values between timezones. It took years for browsers to get this kind of power with dates and times (still, not perfect in Javascript land).