Change datetime in PHP

Use this code to change datetime fields from our API to your desired timezone

Toky API endpoints like CDRs returns data in GTM timezone, so you could need to convert the date to your desired timezone. The following function could help you to convert a datetime variable from one timezone to another.

<?php
function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
?>
  • $dateString: Date in format "Y-m-d H:i:s" like 2019-10-30 20:00:00
  • $timeZoneSource: timezone for the date to convert, for Toky all the dates are in "GMT"
  • $timeZoneTarget your desired timezone.

📘

Example

For converting the date 2019-10-30 20:00:00 from GMT to America/New_York you can use the function:

changeTimeZone("2019-10-30 20:00:00", "GMT", "America/New_York")

This is the implementation and sample code for the function:

<?php
//Timezone conversion function
function changeTimeZone($dateString, $timeZoneSource = null, $timeZoneTarget = null)
{
  //Check valid source timezone 
	try{ 
		new DateTimeZone($timeZoneSource); 
	} catch(Exception $e){ 
		$timeZoneSource = date_default_timezone_get(); 
	}
	//Check valid target timezone 
	try{ 
		new DateTimeZone($timeZoneTarget); 
	} catch(Exception $e){ 
		$timeZoneTarget = date_default_timezone_get(); 
	}  
  //Execute conversion
  $dt = new DateTime($dateString, new DateTimeZone($timeZoneSource));
  $dt->setTimezone(new DateTimeZone($timeZoneTarget));

  return $dt->format("Y-m-d H:i:s");
}

//Sample data
$dt= new DateTime("2019-10-30 20:00:00");//->format("Y-m-d H:i:s");

$initialDate= $dt->format("Y-m-d H:i:s");

$convertedDate = changeTimeZone($dt->format("Y-m-d H:i:s"),"GMT","America/New_York");
echo "Initial date: $initialDate in GMT timezone";
echo "<br/>";
echo "Converted date: $convertedDate in America/New_York";
?>