Home javascript Compare dates.

Compare dates.

Author

Date

Category

Hello. Today’s date is:

var nowDate = new Date ()

And there is some other date otherDate .
Question: How to determine if otherDate is yesterday or even earlier (more than one day ago)?
Yes, and also, how to determine today’s date?


Answer 1, authority 100%

var now = new Date ()

date only:

var today = new Date (now.getFullYear (), now.getMonth (), now.getDate ())

yesterday:

var yesterday = new Date (today.valueOf () - 86400000);

comparison as in the question:

var now = new Date ()
var today = new Date (now.getFullYear (), now.getMonth (), now.getDate ()). valueOf ()
var other = otherDay.valueOf ()
if (other & lt; today - 86400000) {// 24 * 60 * 60 * 1000
  // earlier than yesterday
} else if (other & lt; today) {
  // yesterday
} else {
  // today or later
}

Answer 2, authority 80%

In short:

d1 = new Date ('2010-10-10');
d2 = new Date ('2010-10-09');
dm = d1 - d2;
if (dm & gt; 86400000) alert ('Yesterday--');
else alert ('Later than yesterday');

Yesterday:

prev = (new Date ((new Date ()) .toDateString ()) - 86400000); // 24 * 60 * 60 * 1000

Answer 3, authority 60%

Determine how many days have passed from otherDate to nowDate

otherDate = new Date (2011,11,10);
nowDate = new Date ();
delta = nowDate.getTime () - otherDate.getTime ();
alert ("Passed" + Math.floor (delta / 1000/60/60/24) + "days");

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions