• 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 Reply Cancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • I Joined Truth Social Using a VPN and Editing Some HTML to Bypass the Phone Verification
  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Thoughts on the Flipper Zero
  • Waiting for an Element to Exist With JavaScript
  • Handling Errors with the Fetch API
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • How To Paginate An Array In Javascript
  • Wild Natural Deodorant Review
  • How To Install Eufy Security Cameras Without Drilling or Using Screws

Recent Comments

  • CJ on Microsoft Modern Wireless Headset Review
  • Dwayne on Microsoft Modern Wireless Headset Review
  • CJ on Microsoft Modern Wireless Headset Review
  • john on Microsoft Modern Wireless Headset Review
  • Dwayne on Why You Should Be Using globalThis Instead of Window In Your Javascript Code

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz