1

I format a date object from a string in javascript but but when i print the formatted date i found it increased two years !!

alert("Date1-Without-conversion:" + document.getElementById(arr[0]).value);
alert("Date2-Without-conversion:" + document.getElementById(arr[1]).value);

it prints:

30/9/2018
04/10/2018

date1Str=document.getElementById(arr[0]).value;
date2Str=document.getElementById(arr[1]).value;

date1 = new Date(date1Str);
date2 = new Date(date2Str);

alert("Date1-After-conversion:" + date1);
alert("Dat2-After-conversion:" + date2);

prints:

Tue Jun 09 2020 00:00:00 GMT+0200(Egypt Standard Time)
Tue Apr 10 2018 00:00:00 GMT+0200(Egypt Standard Time)

the problem is that when i used:

date1.getFullYear() OR `date2.getFullYear()` it prints 2020 !!!

How come ??

Java Player
  • 6,050
  • 26
  • 99
  • 154
  • 3
    My guess - it is converting the month 30 to 12*2 + 6, which is june, 2 years ahead. Hence the result – karthikr Sep 09 '13 at 17:31
  • 2
    Just want to add that your code is reading your dates wrong, it is looking at the first number as the month, not as the day. For example, your seconds date is read as April, when you really want October. – Jordan Sep 09 '13 at 17:31
  • 1
    format your string to be 9/30/2018 – Vic Sep 09 '13 at 17:35
  • I recommend using [Moment.js](http://momentjs.com). It is now one of my "standard" libraries whenever I have to deal with dates or times - and makes parsing of custom formats easy (and explicit) as well as being able to detect invalid dates. – user2246674 Sep 09 '13 at 17:57
  • Possible duplicate of [How to format a JavaScript date](http://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – John Slegers Feb 19 '16 at 21:46

2 Answers2

2

Date's parsing leaves something to be desired, as the comments note. You can use this constructor to be succinct

new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]
1

You need to parse the date by parts.

var date1 = new Date(day, month, year);

For 30/9/2018:

var date1 = new Date(30, 9, 2018);
Bart
  • 1,991
  • 13
  • 19
sudhAnsu63
  • 5,510
  • 4
  • 34
  • 50