Handling dates in Javascript

By fritz

A few pointers.

Comparing Dates

If you have two date objects, you need to compare thei values returned by their valueOf or getTime methods:

date1.valueOf() > new Date().valueOf()

If you are only after the difference in days, the best way of doing it is:

Math.floor( ( date1 - date2 ) / 86400000 );

Working with weeks

To find the start of the week:

var start = 1; //Mon=1, Tue=2,.., Sun=7
date1.setDate( date1.getDate() - ( date1.getDay() + 7 - start ) % 7 )

Leave a Reply