0

I have this very simple function that doesnt work on Firefox or IE. Just wondering if you have some insight.

function compareDates(obj, fecha){
    var date1 = new Date( Date.parse(obj.value.replace(/-/g, " ")) );   
    var date2 = new Date( Date.parse(fecha.value.replace(/-/g, " ")) );

    if(date1 < date2){
        alert("Invalid Date");
    }
}

This function receives a 10-JUL-13 and a 20-JUL-13, for examples.

In IE, I don't get the alert, in Chrome, I do get the alert. Please see http://jsfiddle.net/ZDtVv/

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • 2
    It doesn't work anywhere, as comparing two different objects will never return true, even if the contents is the same. – adeneo Jul 10 '13 at 20:20
  • What do you mean when you say "Doesn't work"? What happens? See http://stackoverflow.com/questions/492994/compare-dates-with-javascript for more. – EricLaw Jul 10 '13 at 20:22
  • @adeneo *Date* instances can be compared with `<` – Šime Vidas Jul 10 '13 at 20:33
  • 2
    @adeneo, using `<` and `>` on Dates will first call `valueOf()`, which returns a number – Ruan Mendes Jul 10 '13 at 20:34
  • @JuanMendes - indeed, but suddenly you're thinking "is this the same date", and you're doing `date1 == date2` and it always fails, as it's not the same object, so always calling `getTime()` before comparing dates is a really good practice. – adeneo Jul 10 '13 at 20:41
  • @adeneo If you want to be paranoid against noob devs, then go for it. This is a simple concept, JS always calls `valueOf` when comparing with `<, >, <=, >=` – Ruan Mendes Jul 10 '13 at 21:34

2 Answers2

1

Date.parse requires an ISO date, which requires the full year. Chrome and Firefox try to figure it out for you, you shouldn't rely on that.

// This works
compareDates({value: '10-JUL-2013'}, {value: '20-JUL-2013'})

See http://jsfiddle.net/ZDtVv/1/

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0

Those date strings are not valid date strings, so you get Date objects that have NaN as their actual timestamp. And NaN < NaN tests false.

Per spec, behavior for invalid date strings is undefined; a JavaScript implementation can turn them into NaN or use whatever heuristics it wants to for parsing them. For example, those dates could be year 13 or year 1913 or year 1413 and those would all be valid behaviors per spec.

Boris Zbarsky
  • 34,758
  • 5
  • 52
  • 55
  • 1
    Because the spec says you can basically do whatever you want to with invalid date strings, and the date-parsing library Chrome uses just happens to do something with these particular strings. There's no guarantee it'll keep working in Chrome. – Boris Zbarsky Jul 10 '13 at 21:19