Timezone adjust between server and client

My hosting server timezone is set to UTC, but I am in Mountain. Finally found an easy way to get times adjusted for my timezone.

Return to blog
Posted: October 15, 2019 19:02

My hosting server timezone is set to UTC, so all my dates are stored for that timezone. I am in Mountain time and would like the times adjusted to reflect that. I did quite a bit of searching that involved various solutions, such as adding and removing time to and from dates, formatting, and such. Some of them were very complicated and overdone.

I finally came across a few posts that I merged together to something rather simple that worked for my needs.

function tzAdjust($dateTimeString, $localTimezone, $dateTimeFormat) {
  $dateTime = date_create($dateTimeString);
  date_timezone_set($dateTime, timezone_open($localTimezone));
  $adjustedDateTimeString = date_format($dateTime, $dateTimeFormat);
  return $adjustedDateTimeString;
}

The function takes in a DateTime, a PHP timezone string, and a date format for the return.

date_create creates the DateTime object from a string date, such as '2019-10-08 09:56:06'.

date_timezone_set sets the timezone for that DateTime object ('America/Edmonton'), and does the adjustment.

date_format takes care of turning it into something readable, such as 'F j, Y H:i' - October 8, 2019 09:56.

This function can be safely called when the server and the client are in the same timezone.