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:
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");