views:

59

answers:

3

The server my PHP script is running on is set to UTC. I can't seem to figure out a way to set all dates to the browser's timezone. All dates displayed are formatted using PHP's date() function.

I know that via JavaScript's getTimezoneOffset() function, I can get the browser's current UTC offset (-4, in my case). How can I tell PHP to use this offset? I can use date_default_timezone_set(), but how do I convert an offset, say -4, to a time zone string, say America/New_York?

Note: The server is running PHP 5.1.6 (with no DateTime class) and I am using CodeIgniter.

A: 

Because Javascript is client based and PHP is server based, they will not communicate. To tell the server the browser time, you will need to send information from the client, perhaps via Ajax, posting the browser time. The target PHP script should then handle/output this as appropriate. One other (obtuse) option is to attempt to geolocate the user based on IP, then guesstimate the correct time for that location- however this is inefficient for this purpose.

Ergo Summary
Can I set a cookie in Javascript, and have PHP read it?
Rocket
You certainly can, however this will require the target PHP code to be reloaded so the cookie is updated.
Ergo Summary
A: 

"I know I can use date_default_timezone_set(), but how do I convert an offset, say -4, to a time zone string, say America/New_York?"

Simply look at the comments associated with the documentation for that function. Comment #99006 does the work for you. You just need to get the timezone offset from the user.

jsumners
I usually look through the comments on PHP doc pages. I don't think I've had enough caffeine yet.
Rocket
A: 

As per the comment above- you could use a cookie...:

Javascript:

var today = new Date();

function SetCookie(cookieName,cookieValue,nDays) {
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}

SetCookie("datecookie", today, 30);

window.location.href=window.location.href

PHP:

echo date("m d Y", strtotime($_COOKIE['datecookie']));
Ergo Summary
So, that's how you set a cookie in JavaScript. Thanks.
Rocket
The function above is an off the shelf repurposable function, the '30' basically means the cookie will expire on 30 days. Typically, if we werent using the today variable globally, we would also put it within the function.
Ergo Summary
Cool, I used on my login page, to set the cookie before the user logs in.
Rocket