php manage timezone

Posted: November 21, 2011 in PHP
<?
	function nowGmt()
	{
		$currDateTime = new DateTime(date('Y-m-d H:i:s'));
		$currDateTime->setTimeZone(new DateTimeZone('GMT'));
		return $currDateTime->format('Y-m-d H:i:s');
	}
	function showDateWithOffset($date,$offset=0,$format='d M Y, h:i:s a') 
	{
		if(is_null($date))
			return '-';
		if($offset > 0)
		{
			$date = date('Y-m-d H:i:s',strtotime($date)+$offset);
		}
		$resultDateTime = new DateTime($date, new DateTimeZone('GMT'));
		if($offset == 0)
			$resultDateTime->setTimeZone(new DateTimeZone('America/New_York'));		
		return $resultDateTime->format($format);
	}
	echo 'GMT-->'.$gmt =nowGmt(); // in database always store in GMT format, store offset using javascript
	echo '<br />offset 0 -->'.showDateWithOffset($gmt,$offset=0) ; // in admin side default timezone is newyork
	echo '<br />offset 19800 -->'.showDateWithOffset($gmt,19800) ; // userside fetch GMT time and offset from database and show in user format
	
	//=== below code will show to change date from one timezone to another =====
	$date = new DateTime('2011-11-21 11:00:00', new DateTimeZone('GMT'));
	echo $date->format('Y-m-d H:i:sP') . "\n";
	
	$date->setTimezone(new DateTimeZone('America/New_York'));
	echo '|<br />'.$date->format('Y-m-d H:i:sP') . "\n";
?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s