tags:

views:

4719

answers:

6

I am confused while using php to handle date/time.

What i am trying to do is this. When a user visits my page i am asking his timezone and then displaying the 'day of week' in his timezone.

I dont want wan to use browser's day. I want to do this calculation in php.

This is how i am trying to achieve it.

I use 1. The timezone entered by user 2. Unix time stamp calculated by php time() function.

But i dont know how to proceed... How would i get the 'day of week' in this timezone.

+1  A: 
$myTimezone = date_default_timezone_get();
date_default_timezone_set($userTimezone);
$userDay = date('l', $userTimestamp);
date_default_timezone_set($myTimezone);

This should work (didn't test it, so YMMV). It works by storing the script's current timezone, changing it to the one specified by the user, getting the day of the week from the date() function at the specified timestamp, and then setting the script's timezone back to what it was to begin with.

You might have some adventures with timezone identifiers, though.

Kalium
+2  A: 

If you can get their timezone offset, you can just add it to the current timestamp and then use the gmdate function to get their local time.

// let's say they're in the timezone GMT+10
$theirOffset = 10;  // $_GET['offset'] perhaps?
$offsetSeconds = $theirOffset * 3600;
echo gmdate("l", time() + $offsetSeconds);
nickf
A: 

"Day of Week" is actually something you can get directly from the php date() function with the format "l" or "N" respectively. Have a look at the manual

edit: Sorry I didn't read the posts of Kalium properly, he already explained that. My bad.

HerdplattenToni
+1  A: 
$dw = date( "w", $timestamp);

Where $dw will be 0 (for Sunday) through 6 (for Saturday) as you can see here: http://www.php.net/manual/en/function.date.php

Béres Botond
A: 

Thanks a lot guys for your quick comments.

This is what i will be using now. Posting the function here so that somebody may use it.

public function getDayOfWeek($pTimezone) {

    $userDateTimeZone = new DateTimeZone($pTimezone);
    $UserDateTime = new DateTime("now", $userDateTimeZone);

    $offsetSeconds = $UserDateTime->getOffset(); 
    //echo $offsetSeconds;

    return gmdate("l", time() + $offsetSeconds);

}

Report if you find any corrections.

A: 

Another quick way:

date_default_timezone_set($userTimezone);
echo date("l");
Andre