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

PhpTimezone

Php Problem Overview


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 Solutions


Solution 1 - Php

<?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.

Solution 2 - Php

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.

Solution 3 - Php

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');

Solution 4 - Php

I'd like to address your third item. There is a library consisting exclusively of immutable classes. For example, here is how you can convert a datetime to another timezone:

(new AdjustedAccordingToTimeZone(
    new FromISO8601('2018-04-25 15:08:01+03:00'),
    new CET()
))
    ->value(); // returns 2018-04-25T13:08:01+01:00

Here is a rationale behind this library. It picks out concepts from a language we use, typically denoted by nouns. You can define them more explicitly by asking a question like "What do I need?".

In this example, first, you need a datetime you want to convert from. So, you need a datetime. It means that there is either an interface or an abstract class representing this concept, or abstraction. And actually there is one: it's ISO8601DateTime. Second, you want to create specific objects with specific properties. For example, you want to create a datetime object from an ISO8601 string. That's what makes this specific datetime special, different from all others. It's the property that surely must be present in its name: FromISO8601 extends ISO8601DateTime. Looking at this, you're quite sure about two things: you're looking at the datetime in ISO8601, because this class extends an abstract class of the same name. and second, this specific class is created from an ISO8601 string.

After that, following the same principle, you have a datetime adjusted according to specific timezone -- hence the class AdjustedAccordingToTimeZone. The second parameter is the timezone you want to convert to.

Here is a quick start entry about this library, and feel free to contribute!

Solution 5 - Php

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);

Solution 6 - Php

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);

Solution 7 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontitelView Question on Stackoverflow
Solution 1 - PhpITroubsView Answer on Stackoverflow
Solution 2 - PhpShubham MathurView Answer on Stackoverflow
Solution 3 - PhpsrpView Answer on Stackoverflow
Solution 4 - PhpVadim SamokhinView Answer on Stackoverflow
Solution 5 - PhpAnmolView Answer on Stackoverflow
Solution 6 - PhpAnmolView Answer on Stackoverflow
Solution 7 - Phpuser2622929View Answer on Stackoverflow