I have been trying to convert between timezones a given date and time.
Code speaks more than words, so here it is:
/**
* Returns the date and time in the n
OK, try this instead:
function changeDateTime($datetime, $input_tz, $output_tz) {
// Return original string if in and out are the same
if($input_tz == $output_tz) {
return $datetime;
}
// Save current timezone setting and set to input timezone
$original_tz = date_default_timezone_get();
date_default_timezone_set($input_tz);
// Get Unix timestamp based on input time zone
$time = strtotime($datetime);
// Start working in output timezone
date_default_timezone_set($output_tz);
// Calculate result
$result = date('Y-m-d H:i:s', $time);
// Set timezone correct again
date_default_timezone_set($original_tz);
// Return result
return $result;
}
$out = changeDateTime("2012-08-10 11:33:33", 'Europe/London', 'Europe/Madrid');
var_dump($out);
Rather than messing about doing all that complicated maths, just let PHP do all the hard work for you ;-)
See it working
If your stumbling on this, it can be done cleaner now with the DateTime Object.
public function convertTZ($dateTimeString, $inputTZ, $outputTZ){
$datetime =
\DateTime::createFromFormat('Y-m-d H:i:s', //input format - iso8601
$dateTimeString,
new \DateTimeZone($inputTZ))
->setTimezone(new \DateTimeZone('$outputTZ'));
//outputs a string, if you want the dateTime obj - remove ->format
return $datetime->format('Y-m-d H:i:s'); //output format
}