1

Why does the following code:

    newDate = "2-24-2014";
    var splitDate = newDate.split('-');
    var dateObj = new Date(Number(splitDate[0]), Number(splitDate[1]) - 1, Number(splitDate[2]));

Produce the following?:

Sat Jun 05 1909 00:00:00 GMT+0100 (GMT Daylight Time)

I know the formatting but not the strange date itself. I was wondering if it had something to do with Number but cant seem to find any answers on this.

sledgeweight
  • 7,685
  • 5
  • 31
  • 45
  • Year should come first : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date. –  Feb 06 '14 at 11:43
  • 1
    @wared `splitDate.unshift() - 1` will face parsing error. so change it to `+(splitDate.unshift()) - 1` – Praveen Feb 06 '14 at 11:49
  • Thanks for your advice @Praveen. I've checked before posting of course and it works with Chrome, maybe not in some other browsers. Let us know :) –  Feb 06 '14 at 11:51
  • @Praveen, What would the differences be between your suggestion above and new Date(Date.parse("2-24-2014"))? Both work but would like to know more! Thanks. – sledgeweight Feb 06 '14 at 11:55
  • You can get a good explanation from [here](http://stackoverflow.com/a/2587398/1671639) also `new Date(Date.parse("2-24-2014"))` won't work in FF think so. In my aboe suggest you are parsing to string where `-` operation can't be performed for `string` dataType. Hence I mentioned it. – Praveen Feb 06 '14 at 11:58
  • Indeed, `'1'+1` gives `"11"` while `'1'-1` gives `0`, I guess it might vary across implementations(?). –  Feb 06 '14 at 12:00
  • @wared Seems weird. Here in this [jsfiddle](http://jsfiddle.net/vKNYy/6/) I checked the typeof the both `splitDate.pop()` => returns `string` whereas `splitDate.unshift()` => returns `number`. So auto data conversion is taking place with unshift think so – Praveen Feb 06 '14 at 12:05
  • 1
    @Praveen Well done! Indeed, `unshift` returns the length of the array : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift. Actually, I've confused `shift` and `unshift`... My bad :/ –  Feb 06 '14 at 14:38
  • 1
    @Praveen Anyway, the following fixed code - I've removed the infected comment :) - `new Date(splitDate.pop(), splitDate.shift() - 1, splitDate.pop())` works with an implicit conversion. I guess the `-` operator doesn't allow string concatenation. –  Feb 06 '14 at 14:42

2 Answers2

1
new Date(Year, Month, Date)

The above is the actual format. Whereas you have given like new Date(Month, Date, Year)

var dateObj = new Date(Number(splitDate[2]), Number(splitDate[0]) - 1, Number(splitDate[1]));
Praveen
  • 55,303
  • 33
  • 133
  • 164
0

the problem is the order of parameters:

new Date(Number(splitDate[2]), Number(splitDate[0]) - 1, Number(splitDate[1]));

or simply do this:

new Date(Date.parse("2-24-2014"))
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35