Jeff Kneller
Jeff Kneller

Reputation: 73

PHP - How to Reformat ISO 8601 Date String to user defined Timezone

I have provided date/time in this format: 2012-10-14T06:00

I can rework the data like this: 6:00am using

<?php
function formatDate($date, $format){
    $output = date($format, strtotime($date));
    return $output;
}
?>

<?php echo formatDate('2012-10-14T06:00', 'g:ia'); ?>

Outputs: 6:00am

Which is great, but how can i adjust the offset using

date_default_timezone_set('America/Los_Angeles');

or

date_default_timezone_set('Europe/Amsterdam);

Which is set to the users timezone (whatever they choose) - the time should be offset between the orginal timezone data and the user provided ('Europe/Amsterdam)

So if they set their default timezone to a different country the time would read 8:00am or 4:00am depending on that timezone offset.

The base timezone will always be in XXXX-XX-XXTXX:XX format.

Any help would greatly be appreciated

Upvotes: 2

Views: 2253

Answers (1)

complex857
complex857

Reputation: 20753

Use the DateTime objects. Manually extracting offsets will not take daytime savings and other quirks into account.

// use the the appropriate timezone for your stamp
$timestamp = DateTime::createFromFormat('Y-m-d\TH:i', '2012-10-14T06:00', new DateTimeZone('UTC'));
// set it to whatever you want to convert it
$timestamp->setTimeZone(new DateTimeZone('Europe/Amsterdam'));
print $timestamp->format('Y-m-d H:i:s');

Upvotes: 4

Related Questions