Convert time and date from one time zone to another in PHP - php

Basically what I need is an script that, when provided with a time and a timezone can return the time in another time zone.
My main issues are:
Where to get the time offset from GMT from - is there a public database available for this?
How to also take into consideration the daylight saving time (DST) differences as well.
How to nicely wrap it all up inside an PHP class - or is there such a class already available?

<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
The above examples will output:
2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45
found on DateTime Manual on php.net
EDIT:
Like Pekka said: The DateTime class exists from 5.2 on and there you first have to find out which of the methods are realy implemented and which one only exist from 5.3 on.

try this, it might help :)
function converToTz($time="",$toTz='',$fromTz='')
{
// timezone by php friendly values
$date = new DateTime($time, new DateTimeZone($fromTz));
$date->setTimezone(new DateTimeZone($toTz));
$time= $date->format('Y-m-d H:i:s');
return $time;
}
A bit description:
The function takes 3 inputs, time to convert, timezone to convert to, current timezone and returns the output in the specified format.

I know its late. For anyone who would want simple function to convert utc to any local time zone
function UTCTimeToLocalTime($time, $tz = '', $FromDateFormat = 'Y-m-d H:i:s', $ToDateFormat = 'Y-m-d H:i:s')
{
if ($tz == '')
$tz = date_default_timezone_get();
$utc_datetime = DateTime::createFromFormat($FromDateFormat, $time, new
DateTimeZone('UTC'));
$local_datetime = $utc_datetime;
$local_datetime->setTimeZone(new DateTimeZone($tz));
return $local_datetime->format($ToDateFormat);
}
echo UTCTimeToLocalTime('2015-07-01 13:30:00','America/Denver');

To convert from the given timezone to the desired timezone, we just have to add/subtract the difference of timezones (in SECONDS) to given timezone.
$my_timestamp = strtotime("2020-09-22 14:07:26");
/*
Convert timezones difference into seconds
from -7:00 to +5:30 have 12hrs and 30min difference
So in seconds, 12.5*60*60 is equaled to 45000 seconds
*/
$time_zone_difference = 45000;
//Use date function to get datetime in your desired formate
echo date("Y-m-d h:i:sa", $my_timestamp + time_zone_difference );
or we can write it like
Below given functions are for additional help.
Convert timezone differences in seconds, (which you can hardcode, if it is fixed throught the project):
function timezoneDifferenceInSec( $source_timezone, $required_timezone){
$a = explode(":",$source_timezone);
$b = explode(":",$required_timezone);
$c = (intval($a[0])*60+intval($a[1]))*60;
$d = (intval($b[0])*60+intval($b[1]))*60;
$diffsec =0;
if($c < $d)
$diffsec = $d-$c;
else
$diffsec = $c-$d;
return $diffsec;
}
//function call
$differenc = timezoneDifferenceInSec("-07:00", "+05:30");
Function to convert DateTime into required Timezone (if difference is known):
//datetime in String and timezone_differe is in int
function convertTimezone( $source_date_time, $timezone_diff_in_sec){
return date("Y-m-d h:i:sa", strtotime($source_date_time) + $timezone_diff_in_sec);
}
//function call
$timestamp = "2020-09-22 14:07:26";
$timezone_difference = 4500; //ie from -07:00 to +05:30
echo convertTimezone( $timestamp, $timezone_difference);

Function to convert DateTime into required Timezone (if difference in seconds among the timezones is known):
example: Timestamp give is "2020-09-22 14:07:26".
Timezones difference in seconds id 4500; //ie from -07:00 to +05:30
// timestamp as in String and timezones_diff_in_sec is in int
function convertTimezone( $timestamp, $timezones_diff_in_sec){
return date("Y-m-d h:i:sa", strtotime($source_date_time) + $timezones_diff_in_sec);
}
Function call (
//function call
$timestamp = "2020-09-22 14:07:26";
$timezone_difference = 4500; //ie from -07:00 to +05:30
echo convertTimezone( $timestamp, $timezone_difference);

Here i use this function for converting datetime into another timezone.
For best result if you convert your datetime into utc timezone and then convert into required timezone then it is better result for it.
function ConvertTimezoneToAnotherTimezone($time, $currentTimezone, $timezoneRequired) {
$dayLightFlag = false;
$dayLgtSecCurrent = $dayLgtSecReq = 0;
$system_timezone = date_default_timezone_get();
$local_timezone = $currentTimezone;
date_default_timezone_set($local_timezone);
$local = date("Y-m-d H:i:s");
/* Uncomment if daylight is required */
// $daylight_flag = date("I", strtotime($time));
// if ($daylight_flag == 1) {
// $dayLightFlag = true;
// $dayLgtSecCurrent = -3600;
// }
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s ");
$require_timezone = $timezoneRequired;
date_default_timezone_set($require_timezone);
$required = date("Y-m-d H:i:s ");
/* Uncomment if daylight is required */
// $daylight_flag = date("I", strtotime($time));
// if ($daylight_flag == 1) {
// $dayLightFlag = true;
// $dayLgtSecReq = +3600;
// }
date_default_timezone_set($system_timezone);
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
if ($dayLightFlag) {
$final_diff = $dayLgtSecCurrent + $dayLgtSecReq;
$date->modify("$final_diff seconds");
}
$timestamp = $date->format("Y-m-d H:i:s ");
return $timestamp;
}
Thank You.

Related

How to convert ISO time inside DateTime to local time?

I create a DateTime object like this
$timestamp = new DateTime('2018-04-23T07:01:05.146000+00:00');
$timestampSql = $messageTimestamp->format('Y-m-d H:i:s');
I then insert the $timestampSql into a timestamp field in my mysql table. But the problem is, that the mysql thinks that this time and date is in whatever timezone the mysql server is, and doesn't realize, that it is in fact originating from an ISO time.
So basically, I need to somehow make sure the ->format outputs the timestamp converted to the current timezone the server is set to.
Here is a way you can easily switch a timezone using the dateTime Object:
function convertDate($dateTime){
$utc = 'UTC';
$newTimZone = 'TimeZone';
$newDateTime = new DateTime($dateTime, new DateTimeZone($utc));
$newDateTime->setTimezone(new DateTimeZone($newTimZone));
return $newDateTime->format('Y-m-d H:i:s');
}
Please check below function for server and user time zone
$time_diff = get_timezone_offset('America/New_York');
if(! function_exists('get_timezone_offset'))
{
/*get time differ user and server */
function get_timezone_offset($remote_tz, $origin_tz = null) {
if($origin_tz === null) {
if(!is_string($origin_tz = date_default_timezone_get())) {
return false; // A UTC timestamp was returned -- bail out!
}
}
$origin_dtz = new DateTimeZone($origin_tz);
$remote_dtz = new DateTimeZone($remote_tz);
$origin_dt = new DateTime("now", $origin_dtz);
$remote_dt = new DateTime("now", $remote_dtz);
$offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
$offset = $offset/60;
return $offset;
}
}
$current_date = date("Y-m-d h:i:sa");
$new_date = $this->time_differction($current_date,$time_diff);
if(! function_exists('time_differction'))
{
/*Return new date and time as per user time zone */
function time_differction($date_time, $time_diff){
$time = strtotime($date_time);
$time = $time - ($time_diff * 60 );
$date = date("Y-m-d H:i:s", $time);
return $date;
}
}

Convert time number to different timezone with php [duplicate]

Can anyone suggest an easy method to convert date and time to different timezones in php?
You can use the datetime object or their function aliases for this:
Example (abridged from PHP Manual)
date_default_timezone_set('Europe/London');
$datetime = new DateTime('2008-08-03 12:35:23');
echo $datetime->format('Y-m-d H:i:s') . "\n";
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo $datetime->format('Y-m-d H:i:s');
Edit regarding comments
but i cannt use this method because i need to show date in different time zones as the user login from different locations
That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.
in the database i need to get the dates in any single timezone, then only it can be processed properly
You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.
An even simpler method looks like this:
date_default_timezone_set('Europe/London'); // your user's timezone
$my_datetime='2013-10-23 15:47:10';
echo date('Y-m-d H:i:s',strtotime("$my_datetime UTC"));
As described in the PHP manual, strtotime() accepts a timezone too, you just have to append it to your datetime.
I recommend you to store all your datetimes in UTC because that way you won't have problems with the daylight savings.
This worked for me and it's pretty clean too!
function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
try {
$dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
$dateTime->setTimezone(new DateTimeZone($userTimeZone));
return $dateTime->format($format);
} catch (Exception $e) {
return '';
}
}
function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
try {
$dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
$dateTime->setTimezone(new DateTimeZone($serverTimeZone));
return $dateTime->format($format);
} catch (Exception $e) {
return '';
}
}
//example usage
$serverDate = $userDate = '2014-09-04 22:37:22';
echo convert_to_user_date($serverDate);
echo convert_to_server_date($userDate);
None of these answers worked for me (I skipped trying code that was overly bulky in size). I also think it's weird to change the default timezone just for a single conversion.
Here is my solution:
function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
{
if (empty($timeZoneSource)) {
$timeZoneSource = date_default_timezone_get();
}
if (empty($timeZoneTarget)) {
$timeZoneTarget = date_default_timezone_get();
}
$dt = new DateTime($dateString, new DateTimeZone($timeZoneSource));
$dt->setTimezone(new DateTimeZone($timeZoneTarget));
return $dt->format("Y-m-d H:i:s");
}
So, to convert to the server default, you would just pass one timezone:
changeTimeZone("2016-10-24 16:28", "Asia/Tokyo");
To convert from the server default to the user, you would leave the 2nd parameter null or blank:
changeTimeZone("2016-10-24 16:28", "", "Asia/Tokyo");
And to switch between 2 timezones unrelated to the default, you would provide 2 timezones:
changeTimeZone("2016-10-24 16:28", "America/New_York", "Asia/Tokyo");
UTC to local:
<?php
$datetime = date("Y-m-d H:i:s");
$utc = new DateTime($datetime, new DateTimeZone('UTC'));
$utc->setTimezone(new DateTimeZone('America/Sao_Paulo'));
echo $utc->format('Y-m-d H:i:s');
?>
DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object
Object oriented style
<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
Procedural style
<?php
$date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
date_timezone_set($date, timezone_open('Pacific/Chatham'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
?>
The above examples will output:
2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45
// Convert date from one zone to another..
/*
$zone_from='Asia/Kolkata';
$zone_to='America/Phoenix';
date_default_timezone_set($zone_from);
$convert_date="2016-02-26 10:35:00";
echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);
*/
function zone_conversion_date($time, $cur_zone, $req_zone)
{
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s");
date_default_timezone_set($cur_zone);
$local = date("Y-m-d H:i:s");
date_default_timezone_set($req_zone);
$required = date("Y-m-d H:i:s");
/* return $required; */
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
return $timestamp = $date->format("Y-m-d H:i:s");
}
<?php
$time='6:02';
$dt = new DateTime($time, new DateTimeZone('America/New_York'));
//echo $dt->format('Y-m-d H:i:s') . PHP_EOL;
$dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
echo $dt->format('H:i') . PHP_EOL;
?>
Try this:
function convertDate($dt, $timeZone) {
$UTC = new DateTimeZone("UTC");
$date= date('Y-m-d H:i:s', strtotime($dt));
$dateConv = new DateTime( $dt, $UTC );
$dateFormat ='m/d/Y h:i A';
$date->setTimezone(new DateTimeZone($timeZone));
return $date->format($dateFormat);
}

date function in PHP - applies timezone? [duplicate]

Can anyone suggest an easy method to convert date and time to different timezones in php?
You can use the datetime object or their function aliases for this:
Example (abridged from PHP Manual)
date_default_timezone_set('Europe/London');
$datetime = new DateTime('2008-08-03 12:35:23');
echo $datetime->format('Y-m-d H:i:s') . "\n";
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo $datetime->format('Y-m-d H:i:s');
Edit regarding comments
but i cannt use this method because i need to show date in different time zones as the user login from different locations
That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.
in the database i need to get the dates in any single timezone, then only it can be processed properly
You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.
An even simpler method looks like this:
date_default_timezone_set('Europe/London'); // your user's timezone
$my_datetime='2013-10-23 15:47:10';
echo date('Y-m-d H:i:s',strtotime("$my_datetime UTC"));
As described in the PHP manual, strtotime() accepts a timezone too, you just have to append it to your datetime.
I recommend you to store all your datetimes in UTC because that way you won't have problems with the daylight savings.
This worked for me and it's pretty clean too!
function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
try {
$dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
$dateTime->setTimezone(new DateTimeZone($userTimeZone));
return $dateTime->format($format);
} catch (Exception $e) {
return '';
}
}
function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
try {
$dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
$dateTime->setTimezone(new DateTimeZone($serverTimeZone));
return $dateTime->format($format);
} catch (Exception $e) {
return '';
}
}
//example usage
$serverDate = $userDate = '2014-09-04 22:37:22';
echo convert_to_user_date($serverDate);
echo convert_to_server_date($userDate);
None of these answers worked for me (I skipped trying code that was overly bulky in size). I also think it's weird to change the default timezone just for a single conversion.
Here is my solution:
function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
{
if (empty($timeZoneSource)) {
$timeZoneSource = date_default_timezone_get();
}
if (empty($timeZoneTarget)) {
$timeZoneTarget = date_default_timezone_get();
}
$dt = new DateTime($dateString, new DateTimeZone($timeZoneSource));
$dt->setTimezone(new DateTimeZone($timeZoneTarget));
return $dt->format("Y-m-d H:i:s");
}
So, to convert to the server default, you would just pass one timezone:
changeTimeZone("2016-10-24 16:28", "Asia/Tokyo");
To convert from the server default to the user, you would leave the 2nd parameter null or blank:
changeTimeZone("2016-10-24 16:28", "", "Asia/Tokyo");
And to switch between 2 timezones unrelated to the default, you would provide 2 timezones:
changeTimeZone("2016-10-24 16:28", "America/New_York", "Asia/Tokyo");
UTC to local:
<?php
$datetime = date("Y-m-d H:i:s");
$utc = new DateTime($datetime, new DateTimeZone('UTC'));
$utc->setTimezone(new DateTimeZone('America/Sao_Paulo'));
echo $utc->format('Y-m-d H:i:s');
?>
DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object
Object oriented style
<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
Procedural style
<?php
$date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
date_timezone_set($date, timezone_open('Pacific/Chatham'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
?>
The above examples will output:
2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45
// Convert date from one zone to another..
/*
$zone_from='Asia/Kolkata';
$zone_to='America/Phoenix';
date_default_timezone_set($zone_from);
$convert_date="2016-02-26 10:35:00";
echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);
*/
function zone_conversion_date($time, $cur_zone, $req_zone)
{
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s");
date_default_timezone_set($cur_zone);
$local = date("Y-m-d H:i:s");
date_default_timezone_set($req_zone);
$required = date("Y-m-d H:i:s");
/* return $required; */
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
return $timestamp = $date->format("Y-m-d H:i:s");
}
<?php
$time='6:02';
$dt = new DateTime($time, new DateTimeZone('America/New_York'));
//echo $dt->format('Y-m-d H:i:s') . PHP_EOL;
$dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
echo $dt->format('H:i') . PHP_EOL;
?>
Try this:
function convertDate($dt, $timeZone) {
$UTC = new DateTimeZone("UTC");
$date= date('Y-m-d H:i:s', strtotime($dt));
$dateConv = new DateTime( $dt, $UTC );
$dateFormat ='m/d/Y h:i A';
$date->setTimezone(new DateTimeZone($timeZone));
return $date->format($dateFormat);
}

UTC Date/Time String to Timezone

How do I convert a date/time string (e.g. 2011-01-01 15:00:00) that is UTC to any given timezone php supports, such as America/New_York, or Europe/San_Marino.
PHP's DateTime object is pretty flexible.
$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');
PHP's DateTime object is pretty flexible.
Since the user asked for more than one timezone option, then you can make it generic.
Generic Function
function convertDateFromTimezone($date,$timezone,$timezone_to,$format){
$date = new DateTime($date,new DateTimeZone($timezone));
$date->setTimezone( new DateTimeZone($timezone_to) );
return $date->format($format);
}
Usage:
echo convertDateFromTimezone('2011-04-21 13:14','UTC','America/New_York','Y-m-d H:i:s');
Output:
2011-04-21 09:14:00
Assuming the UTC is not included in the string then:
date_default_timezone_set('America/New_York');
$datestring = '2011-01-01 15:00:00'; //Pulled in from somewhere
$date = date('Y-m-d H:i:s T',strtotime($datestring . ' UTC'));
echo $date; //Should get '2011-01-01 10:00:00 EST' or something like that
Or you could use the DateTime object.
function _settimezone($time,$defaultzone,$newzone)
{
$date = new DateTime($time, new DateTimeZone($defaultzone));
$date->setTimezone(new DateTimeZone($newzone));
$result=$date->format('Y-m-d H:i:s');
return $result;
}
$defaultzone="UTC";
$newzone="America/New_York";
$time="2011-01-01 15:00:00";
$newtime=_settimezone($time,$defaultzone,$newzone);
General purpose normalisation function to format any timestamp from any timezone to other.
Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')
/**
* Convert Datetime from any given olsonzone to other.
* #return datetime in user specified format
*/
function datetimeconv($datetime, $from, $to)
{
try {
if ($from['localeFormat'] != 'Y-m-d H:i:s') {
$datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
}
$datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
$datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
return $datetime->format($to['localeFormat']);
} catch (\Exception $e) {
return null;
}
}
Usage:
$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta'];
$to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC'];
datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"
How about:
$timezone = new DateTimeZone('UTC');
$date = new DateTime('2011-04-21 13:14', $timezone);
echo $date->format;

Timezone conversion in php

Can anyone suggest an easy method to convert date and time to different timezones in php?
You can use the datetime object or their function aliases for this:
Example (abridged from PHP Manual)
date_default_timezone_set('Europe/London');
$datetime = new DateTime('2008-08-03 12:35:23');
echo $datetime->format('Y-m-d H:i:s') . "\n";
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo $datetime->format('Y-m-d H:i:s');
Edit regarding comments
but i cannt use this method because i need to show date in different time zones as the user login from different locations
That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.
in the database i need to get the dates in any single timezone, then only it can be processed properly
You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.
An even simpler method looks like this:
date_default_timezone_set('Europe/London'); // your user's timezone
$my_datetime='2013-10-23 15:47:10';
echo date('Y-m-d H:i:s',strtotime("$my_datetime UTC"));
As described in the PHP manual, strtotime() accepts a timezone too, you just have to append it to your datetime.
I recommend you to store all your datetimes in UTC because that way you won't have problems with the daylight savings.
This worked for me and it's pretty clean too!
function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
try {
$dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
$dateTime->setTimezone(new DateTimeZone($userTimeZone));
return $dateTime->format($format);
} catch (Exception $e) {
return '';
}
}
function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
{
try {
$dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
$dateTime->setTimezone(new DateTimeZone($serverTimeZone));
return $dateTime->format($format);
} catch (Exception $e) {
return '';
}
}
//example usage
$serverDate = $userDate = '2014-09-04 22:37:22';
echo convert_to_user_date($serverDate);
echo convert_to_server_date($userDate);
None of these answers worked for me (I skipped trying code that was overly bulky in size). I also think it's weird to change the default timezone just for a single conversion.
Here is my solution:
function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
{
if (empty($timeZoneSource)) {
$timeZoneSource = date_default_timezone_get();
}
if (empty($timeZoneTarget)) {
$timeZoneTarget = date_default_timezone_get();
}
$dt = new DateTime($dateString, new DateTimeZone($timeZoneSource));
$dt->setTimezone(new DateTimeZone($timeZoneTarget));
return $dt->format("Y-m-d H:i:s");
}
So, to convert to the server default, you would just pass one timezone:
changeTimeZone("2016-10-24 16:28", "Asia/Tokyo");
To convert from the server default to the user, you would leave the 2nd parameter null or blank:
changeTimeZone("2016-10-24 16:28", "", "Asia/Tokyo");
And to switch between 2 timezones unrelated to the default, you would provide 2 timezones:
changeTimeZone("2016-10-24 16:28", "America/New_York", "Asia/Tokyo");
UTC to local:
<?php
$datetime = date("Y-m-d H:i:s");
$utc = new DateTime($datetime, new DateTimeZone('UTC'));
$utc->setTimezone(new DateTimeZone('America/Sao_Paulo'));
echo $utc->format('Y-m-d H:i:s');
?>
DateTime::setTimezone -- date_timezone_set — Sets the time zone for the DateTime object
Object oriented style
<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
Procedural style
<?php
$date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
date_timezone_set($date, timezone_open('Pacific/Chatham'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
?>
The above examples will output:
2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45
// Convert date from one zone to another..
/*
$zone_from='Asia/Kolkata';
$zone_to='America/Phoenix';
date_default_timezone_set($zone_from);
$convert_date="2016-02-26 10:35:00";
echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);
*/
function zone_conversion_date($time, $cur_zone, $req_zone)
{
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s");
date_default_timezone_set($cur_zone);
$local = date("Y-m-d H:i:s");
date_default_timezone_set($req_zone);
$required = date("Y-m-d H:i:s");
/* return $required; */
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
return $timestamp = $date->format("Y-m-d H:i:s");
}
<?php
$time='6:02';
$dt = new DateTime($time, new DateTimeZone('America/New_York'));
//echo $dt->format('Y-m-d H:i:s') . PHP_EOL;
$dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
echo $dt->format('H:i') . PHP_EOL;
?>
Try this:
function convertDate($dt, $timeZone) {
$UTC = new DateTimeZone("UTC");
$date= date('Y-m-d H:i:s', strtotime($dt));
$dateConv = new DateTime( $dt, $UTC );
$dateFormat ='m/d/Y h:i A';
$date->setTimezone(new DateTimeZone($timeZone));
return $date->format($dateFormat);
}

Categories