-2

code:

var userDate = "7/9/2016"
    var d = new Date(userDate);
    var daTe = d.toLocaleString();

 var today = "7/27/2016"
    var md = new Date(today);
    var td = md.toLocaleString();

    if (daTe > td) {
        alert("YES!")
    }

how come the userDate is greater than today? when I use 7/2/2016 to 7/9/2016 on userDate as value? Please explain.

Jostine
  • 51
  • 1
  • 6

1 Answers1

4

toLocaleString() returns a string, so you're comparing two strings, not two dates. If you want to compare the dates, you can compare either the date objects themselves, or their timestamps.

Both of these will return false:

d > md
d.getTime() > md.getTime()
rid
  • 61,078
  • 31
  • 152
  • 193
  • Just adding this link (http://stackoverflow.com/questions/7087811/why-is-one-string-greater-than-the-other-when-comparing-strings-in-javascript) for an overview if you compare strings as mentioned within the question. Quote: "strings are compared lexicographically" – oberbics Jul 27 '16 at 08:10