Convert Date And Time To Different Timezone In PHP

Convert Date And Time To Different Timezone In PHP

It provides code examples to convert the date and time to a different timezone in PHP.

June 03, 2020

This tutorial provides code examples to convert the date and time value from one timezone to another timezone using DateTime and DateTimeZone classes. We can always convert the date and time value from the active timezone to a different timezone.

The below-mentioned examples show the conversion of the given date and time from UTC timezone to the Los Angeles timezone. It further converts the date and time from the Los Angeles timezone to the London timezone.

// Get Timezone - UTC
$utcTimezone = new DateTimeZone( 'UTC' );

// Set time
$time = new DateTime( '2020-06-03 10:45:15', $utcTimezone );

echo $time->format( 'Y-m-d H:i:s' ); // 2020-06-03 10:45:15

// Get Timezone - Los Angeles
$laTimezone = new DateTimeZone( 'America/Los_Angeles' );

$time->setTimeZone( $laTimezone );

// Convert UTC to Los Angeles
echo $time->format( 'Y-m-d H:i:s' ); // 2020-06-03 03:45:15

// Get Timezone - London
$loTimezone = new DateTimeZone( 'Europe/London' );

$time->setTimeZone( $loTimezone );

// Convert Los Angeles to London
echo $time->format( 'Y-m-d H:i:s' ); // 2020-06-03 11:45:15

We can do multiple timezone conversions as shown above to show multiple clocks, keeping UTC as the standard timezone.

We can also use the function date_default_timezone_set to set the default timezone and use a different timezone to convert the date and time from the default timezone to the given timezone as shown below.

<?php
// Globally define the Timezone
define( 'TIMEZONE', 'UTC' );

// Set Timezone
date_default_timezone_set( TIMEZONE );

// Set time
$time = new DateTime( '2020-06-03 10:45:15' );

echo $time->format( 'Y-m-d H:i:s' ); // 2020-06-03 10:45:15

// Get Timezone - Los Angeles
$laTimezone = new DateTimeZone( 'America/Los_Angeles' );

$time->setTimeZone( $laTimezone );

// Convert UTC to Los Angeles
echo $time->format( 'Y-m-d H:i:s' ); // 2020-06-03 03:45:15

This is the easiest way to convert the time from one clock to another using the DateTime and DateTimeZone classes.

Write a Comment
Click the captcha image to get new code.
Discussion Forum by DISQUS