Page 1 of 1

Convert timezones?

Posted: Mon Apr 26, 2010 12:51 am
by Cirdan
There is nothing I hate more(maybe form validation scripts) than dealing with dates, times, and timezones. Just terrible.

I have a method that is called whenever I want to output a readable date(all of my dates and times are stored as unix timestamps). In the method, I want it to convert the time based on the user's timezone.

Code: Select all

public function formatDate($timestamp, $time = false) {
		$dateformat = Model_CurrentUser::getInstance()->dateFormat;
		$timeformat = Model_CurrentUser::getInstance()->timeFormat;
		$timezone = Model_CurrentUser::getInstance()->timezone;
		//$result = '';
		
		$date = new DateTime(date('r', $timestamp), new DateTimeZone($timezone));
                // .............
                // Then at the end of the method
		$result = $date->format($dateformat);

		return $result;
Shouldn't this convert the time from the server time from date('r') to the timezone I get from the user's settings? The $timestamp passed to this method is generated with time(). The timezones for the users are stored like 'America/Indianapolis'.

Re: Convert timezones?

Posted: Mon Apr 26, 2010 1:06 am
by Zyxist
No, it shouldn't. The constructor ignores the timezone, if it is already set in the formatted date. And in case of date('r') it is:

Thu, 21 Dec 2000 16:01:07 +0200

You can set the timezone once with date_default_timezone_set() function called somewhere and it will affect everything:

Code: Select all

<?php
date_default_timezone_set('Europe/Warsaw');

$date = new DateTime('now');
echo $date->format('d.m.Y, H:i').'<br/>';

Re: Convert timezones?

Posted: Mon Apr 26, 2010 12:01 pm
by Cirdan
EDIT: Found the problem. I guess "new DateTimeZone" sets the variable immediately, instead of after the constructor has finished.

I found a tutorial, and changed the code to this:

Code: Select all

		$timezone = new DateTimeZone($timezone);
		$date = new DateTime(date('r', $timestamp));
		$date->setTimezone($timezone);
However for some really strange reason, the $timezone = new DateTimeZone() screws everything up. Basically causing my layout system to output the page (very)incorrectly. If I comment out that line, everything is fine. I tried try-catch but that didn't output an errors.