[SOLVED] How to Change Date Format from UTC Timezone to Any Required Timezone

By dhanyamol.kv | 17th December 2018 | 1 min read

In Drupal, usually the date field value is saved in the database in UTC timezone format. One of our requirements for a project was to show the date in the site's timezone format. So we generated a general function to convert date in UTC timezone to any required timezone and format it.

Just use the below function to convert date in UTC timzone to a given timezone and the format date using a valid timestamp,

 * Function to get date/time on user's timezone
 * @param  int $timestamp
 *  Timestamp to be converted to date
 * @param string timezone
 *  Timezone to which date is to be converted
 * @param  string $format
 *  Format to which date to convert
 * @return string
 *  Formatted date.
function get_date_on_given_timezone($timestamp, $new_timezone, $format = 'd/m/Y H:i:s') {
  if (!empty($timestamp)) {
    // Database timezone.
    $db_timezone = 'UTC';
    $date_object = new DateObject($timestamp, new DateTimeZone($db_timezone));
    // Convert from the database time zone to site's time zone.
    $date_object->setTimezone(new DateTimeZone($new_timezone));
    $new_date = date_format_date($date_object, 'custom', $format);
    return $new_date;

Hope this snippet is helpful for you.