tags:

views:

113

answers:

4

I have a bizzare problem with php date function.

code:

$numDays = 8;
$date = strtotime('2010-11-06');
for ($i=1; $i<=$numDays; $i++)
{
    $thisDay = date("D, d M Y", $date);
    print ($thisDay.'<br>');
    $date+=86400; // add one day to timestamp
}

result on my server (local host, windows):

Sat, 06 Nov 2010

Sun, 07 Nov 2010

Mon, 08 Nov 2010

Tue, 09 Nov 2010

Wed, 10 Nov 2010

Thu, 11 Nov 2010

Fri, 12 Nov 2010

Sat, 13 Nov 2010

Result on my web server (linux)

Sat, 06 Nov 2010

*Sun, 07 Nov 2010

Sun, 07 Nov 2010*

Mon, 08 Nov 2010

Tue, 09 Nov 2010

Wed, 10 Nov 2010

Thu, 11 Nov 2010

Fri, 12 Nov 2010

Notice how Sun, 07 Nov 2010 appears twice on the remote server?? Why is this happening? can anyone explain this Behavior?

+2  A: 

Daylight saving time?

Mihai
Useful as a hint to set timezone, but Pekka's was more detailed and in depth so I accepted his. Thank you :)
Spiros
+6  A: 

November 7, 2010 is the DST switch date in many time zones (but not Greece where you seem to be located). From Wikipedia:

Starting in 2007, most of the United States and Canada observe DST from the second Sunday in March to the first Sunday in November, almost two-thirds of the year.

In Greece, it seems to be October 31. Which time zone do you have you set on your machine?

Pekka
You are right, if I set Athens timezone ( Europe/Athens ) the dates appear correct. However this means that if the user is in USA or Canada the above code will not work! if I use US/Pacific as timezone for example I get the wrong results. Is there a straightforward way to solve this?
Spiros
@spiros I *think* `strtotime("+1 day");` will take DST into consideration.
Pekka
If you're pulling the data from a database server, you might be better off doing the date manipulation there; Postgres, in particular, is good here. Timestamps stores with a time zone can simply be cast into another time zone and the database handles all the daylight savings, etc (I don't think light speed, mentioned above, is accounted for, however) - more information at http://www.postgresql.org/docs/8.3/static/datatype-datetime.html#DATATYPE-TIMEZONES. MySQL date functions tend to be, in my experience, relatively crap, but someone else may have more info.
El Yobo
+1  A: 

Run your code with the starting date +1 hr and then -1hr and see what results you get. You'll get more clues and most likely it is to do with Daylight Saving Time.

Also, as pointed out by Pekka, try the same with the date set to Oct 31st and see what happens.

Good question.

zaf
+1  A: 

It's good practice to do time calculations in UTC and then convert them to the required timezone for the user's location using PHPs datetime functions:

date_default_timezone_set('UTC');
$timezone = new DateTimeZone('Europe/Athens');
$datetime = new DateTime('now', $timezone);
echo $datetime->format('Y-m-d H:i:s');
ImCr