Welcome to WebmasterWorld Guest from 54.145.173.36

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Trying to make my PHP countodown work for users timezone

   
10:58 pm on Oct 31, 2011 (gmt 0)

10+ Year Member



Working on a little Christmas countdown and I have the following php:

$today = getdate();
$xmas=$today[year]."-12-25";
$datetime2 = new DateTime("$xmas");
$datetime1 = new DateTime();
$interval = $datetime1->diff($datetime2);
$untilxmas=$interval->format('%a');


As I tested it, I realized that the answers were based on my server's timezone. I have access to a variable with the visitors offset from GMT, so what would I need to do to make it so my script would have a different answer for someone in New York vs. Vancouver?

Thanks!
12:17 am on Nov 1, 2011 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



There are a number of ways to handle this, ianevans, but since you are using the DateTime() class, how about passing the DateTimeZone object to it?
[php.net...]
2:44 am on Nov 1, 2011 (gmt 0)

10+ Year Member



Hmm, I thought from my reading that the DateTimeZone only took text zones like "Pacific/Nauru". I'm doing this on Facebook and have access to an offset variable like "-4". How can I use that?

Total beginner on using DateTime...just discovered it yesterday, so your help is not only appreciated...it's necessary! :)
7:30 am on Nov 1, 2011 (gmt 0)

WebmasterWorld Administrator httpwebwitch is a WebmasterWorld Top Contributor of All Time 10+ Year Member



It's easy to do without all the DateTime() stuff. Just use Unix timestamps.

1 hour = 3600 seconds.

so, if the time zone, $tz, is -4, the offset in seconds is (-4 * 3600) seconds from UTC.

$datetime1 = time() + ($tz * 3600);

then, if you want it formatted pretty:

$datestr = date("Y-m-d H:i:s", $datetime1);

tada!
11:21 am on Nov 1, 2011 (gmt 0)

10+ Year Member



Thanks httpwebwitch. How would I calculate the correct Xmas date? use gmmktime to create the dec 25 timestamp and then + ($tz * 3600);

i.e.

xmas= gmmktime(0,0,0,12,25,2011) + ($tz * 3600);
9:47 pm on Nov 1, 2011 (gmt 0)

10+ Year Member



hmmm...it seems my time() is returning the time in my zone because when I "$datetime1 = time() + ($tz * 3600); " I'm getting four hours behind my time not four hours behind GMT.