PHP: Convert UTC to CET (Coordinated Universal Time to Central European Time)

Today I was trying like hell to find a way to convert a date and time given in the Coordinated Universal Time format (UTC) to the corresponding date (and especially time) in CET.
Yes, it’s that easy, one might say – but how can the daylight saving times be included?

First I tried to extract all data information from the string using the substr function of PHP. Let’s say the given time in UTC format is 2012-07-02T13:17:19.000Z, which corresponds to July 2nd, 2012 at 1:17:19 p.m. GMT (as UTC ‘is equal’ to GMT).
That following piece of code was the result of that, but didn’t lead to a solution for my problem.

// given UTC time
$utcDateTime = "2012-07-02T13:17:19.000Z";
// extract date and time information
$year = substr($utcDateTime, 0, 4);
$month = substr($utcDateTime, 5, 2);
$day = substr($utcDateTime, 8, 2);
$hour = substr($utcDateTime, 11, 2);
$minute = substr($utcDateTime, 14, 2);
$second = substr($utcDateTime, 17, 2);
// combine to timestamp
$timestamp = mktime($hour, $minute, $second, $month, $day, $year);

As you see, you do easily get a timestamp out of it. If you’re searching for sth. like that, please feel free to use it.

I found a lot of PHP  scripts on more or less related topics/problems, but none that could solve mine. Then I stumbled across a piece of code (sorry for not providing the URL, but the browser tab got lost somehow) where the PHP function strtotime was used to recalculate the server’s time in EST (Eastern Standard Time – US, e.g. New York) to a time in CET (Central European Time – e.g. Paris or Berlin).

After reading, what strtotime actually does, I thought, well, give it a try with the UTC formatted time. And it worked – resulting in that little function.

// still having our UTC time from the example above
$utcDateTime = "2012-07-02T13:17:19.000Z";
function utc2cet($utcDateTime) {
// set your local timezone
// convert utc time format to unix timestamp
$utcDateTimeTimestamp = strtotime($utcDateTime);
// convert to human readable local time (2nd is udjustable using setlocale)
echo 'my date and time is '. date("d.m.Y, H:i:s", $utcDateTimeTimestamp) .'<br />';
echo strftime("%A, %d.%B.%Y, %H:%M:%S", $utcDateTimeTimestamp);
//  call function with UTC time
utc2cet( $utcDateTime );

It’s easily adjustable to have other time zones converted too – one may add a second variable to the function’s call, where the wanted time zone is given.

You may even just return the $utcDateTimeTimestamp and ‘style’ it using date() in your main code.

I hope that helps and sorry for the ugly formatted code, but WordPress is not capable of enclosing code by default (at least I didn’t find it).

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA request error. Details: Error. No connection.