• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

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

PHP · October 1, 2021

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).

Dwayne

Leave a ReplyCancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • Handling Errors with the Fetch API
  • How To Get The Hash of A File In Node.js
  • Thoughts on the Flipper Zero
  • How To Paginate An Array In Javascript
  • Testing Event Listeners In Jest (Without Using A Library)

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz