[thelist] JS calculations on Date object

Steve Webster steve at netbreed.co.uk
Mon Sep 30 12:31:01 CDT 2002


>I'm working on a JavaScript solution to expire some pages.  Once a
>certain date has arrived, the page will have expired and the user will
>be redirected to a "the page you're trying to view has expired" page.
>However, to try and be a little more helpful, I'd like to show a message
>on the screen that says something like "this page will expire in 5 days
>- please contact the document owner".  I've got part of the way there,
>but I can't work out how to take 2 dates away from each other to give a
>value left in days.  So far, I've got this, which works:
>function checkexpired()
>var expireDate
>var todaysDate
>expireDate = new Date("September 28, 2002") //this is the date the page
>todaysDate = new Date()  //this is today's date
>if (todaysDate > expireDate)
>location.href="http://www.foo.com" //this is the redirection page
...add in...

     daysLeft = Math.floor((expireDate.getTime() - todaysDate.getTime())
/ (1000 * 60 * 60 * 24));


The getTime() method returns the number of milliseconds since 1 January
1970 for the given date object. By subtracting this value for the
current date from the equivalent value for the expiry date, and dividing
the result by the number of milliseconds in a day, we get the difference
in days between the two dates. We use Math.floor() to round the number
of days down to the nearest whole number.

You can then use daysLeft in a document.write() call to output the
number of days remaining!

I hope this helps!



More information about the thelist mailing list