I have a curious problem with using unix timestamps to work out date differences.

My user need to enter a start date and number of nights (its a vacation booking system).

I need to work out the departure date by adding the number of nights to the start date.

I use code as follows:

// $arrday, $arrmonth, $arryear and $nights are entered into web form, e.g. 12, 1, 2002, 7
// 86400 = 606024 - i.e. adder for one day to unix timestamp

$arrtime = mktime(0,0,0,$arrmonth,$arrday,$arryear);
$deptime = $arrtime + ($nights * 86400);
$depday = date("j",$deptime);
$depmonth = date("n",$deptime);
$depyear = date("Y",$deptime);

For the most part this works fine. However, some date combinations result in odd answers.

For example:

$arrday 22
$arrmonth 10
$arryear 2002
$nights 3

results in

$depday 25
$depmonth 10
$depyear 2002

which is correct, but

$arrday 25
$arrmonth 10
$arryear 2002
$nights 3

results in

$depday 27
$depmonth 10
$depyear 2002

which is not. It should be 28,10,2002. This happens with 25/10/2002 to 27/10/2002. There is also a period in April when this happens and there may be more.

What am I doing wrong?

Thanks,

Cris

    sounds strange.

    Try changing mktime to use 12, 0, 0, month, day, year instead of 0, 0, 0, month, day, year. This shifts the time to midday. May be a rounding issue somewhere.

    Anyhow - see what happens.

      Thanks. That got those dates working properly. Lets hope it doesn't just move the problem. I'll probably post a trouble report on this on php.net. It does seem to be a real sneaaky problem with the php code.

      Thanks again.

      Cris

        Not sure about the exact dates, but don't the clocks go back & forward at those times of the year..... October & April. Not really a fault of PHP I'm sure...

          Spot on! I should have realised.

          It is a daylight savings time issue - not a problem with PHP. I simply followed the first suggestion and worked on midday instead of midnight to get over the problem.

          Thanks for everyones help. Much Appreciated.

          Cris

            Write a Reply...