[thelist] JS calculations on Date object

Steve Webster steve at netbreed.co.uk
Mon Sep 30 15:48:02 CDT 2002


Steve Webster wrote:

> fstorr wrote:
>
>> [snip]
>>
>> Cheers for that Steve and also for the explanation - very helpful.  One
>> question - if I set todaysDate and expireDate to the same day, daysLeft
>> is equal to -1.  Shouldn't this be 0 (and if so, I'll whack a +1 at the
>> end of the line)?
>>
>>
> Surely that's not necessary, since if today's date is the expiry date
> then you'll be redirecting the visitor?
>
> If you really need to fix this, then add the following like of code
> after creating the Date object for todaysDate...
>
>    todaysDate.setTime(todaysDate.getTime() - (todaysDate.getTime() %
> (1000 * 60 * 60 * 24)) + (todaysDate.getTimezoneOffset() * 60 * 1000));
>
> This removes the time element of the current date, factoring in the
> timezone difference, so that both dates fall on midnight of their
> respective days, making calculations much easier!

Not to mention accurate :o)

The problem was that the expireDate is set without providing a time
element, so the time is assumed to be midnight on the date given. The
todaysDate, however, is set to the current time and date, and thus when
manipulating values returned from the getTime() method, the latter is a
larger value. and causes the calculation to result in -1 as opposed to 0
as expected.

Regards,

Steve





More information about the thelist mailing list