Web development · 30 Aug 2014 · 2 min read

Convert time from one timezone to another

When you need to convert time from one timezone to another, the simplest approach is to store the time in UTC and only convert it to the timezone you need when you display or use it. PHP’s DateTime functions make this straightforward.

For example, if you want to email users at a specific local time, save their chosen time in UTC along with their timezone. Then, when a cron job runs to send the emails, convert the current time into each user’s timezone and compare it against the saved time.

Here’s a simple function that converts a time value between two timezones:

function convertToTz($time = "", $toTz = '', $fromTz = '')
{
    // Convert between timezones using PHP's DateTime classes.
    $date = new DateTime($time, new DateTimeZone($fromTz));
    $date->setTimezone(new DateTimeZone($toTz));
    $time = $date->format('Y-m-d H:i:s');
    return $time;
}

Use it to convert a user’s time when you first save it, and again whenever you need to check it later. PHP’s DateTime functions support the full list of standard timezone identifiers.

$time = "2012-01-23 10:30:00"; // Time selected by the user for their email.
$timezone = "Asia/Kolkata";
$saveTimeToDatabase = convertToTz($time, 'UTC', date('e')); // Convert from server time to UTC.
// Save $saveTimeToDatabase and $timezone against the user's record.

// Later, when checking whether it's time to send the email:
$userTime = "2012-01-23 05:00:00"; // Time saved for the user, in UTC.
$userTimezone = "Asia/Kolkata";
$userConvertedTime = convertToTz($userTime, $userTimezone, 'UTC');

if (date('Y-m-d H:i:s') == $userConvertedTime) {
    mail('admin@example.com', 'Time to send');
}

Have a tender deadline or a system that needs rescuing?

Tell us the scope. We'll come back within one working day with a plan and a number.

Talk to us

Peak performance
& connectivity

31.10°N 77.17°E — Kasumpti, Shimla — 2,205 m