1

When i am trying to compare the two dates using date.toLocaleString() it is not giving the correct answer for some months date.

var date1 = new Date();
var date2 = new Date((new Date()).valueOf() + 1000*3600*24);
if(date1.toLocaleDateString() < date2.toLocaleDateString())
{
  alert("Correct");
}
else
{
  alert("Incorrect");
}

Can anyone have solution for this.

Anmol Nijhawan
  • 835
  • 1
  • 8
  • 15
  • Why are you comparing strings when you can compare Dates directly using `date1 < date2`? The output of *toLocaleString* is **entirely** implementation dependent, so consistent results of comparisons is extremely unlikely. Also see [*How can I add 1 day to current date?*](https://stackoverflow.com/questions/9989382/how-can-i-add-1-day-to-current-date) – RobG Feb 20 '18 at 22:34

2 Answers2

2

toLocaleDateString for todays date is 2018-2-21 where as for the month november, it is 2018-11-21. So in terms of string comparisons, november month will be considered to have a lesser value than todays date.

Use Timestamp to compare dates.

var date1 = new Date(),
    date2 = new Date((new Date()).valueOf() + 1000*3600*24)

if(date1.getTime() < date2.getTime()) {
  alert("Correct");
} else {
  alert("Incorrect");
}
Akash Dathan
  • 4,348
  • 2
  • 24
  • 45
0

Try this:-

var date1 = new Date();
    var date2 = new Date((new Date()).valueOf() + 1000*36000*24);
    if(date1.getTime() < date2.getTime())
    {
      alert(""+date1+"Smaller then \n "+date2);
    }
    else
    {
      alert(""+date1+"\n "+date2);
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Mr Singh
  • 3,936
  • 5
  • 41
  • 60
  • 1
    Why is jQuery included? A good answer should include why the OP has their issue and how your code fixes it. – RobG Feb 20 '18 at 22:35