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 ??

5
  • 3
    My guess - it is converting the month 30 to 12*2 + 6, which is june, 2 years ahead. Hence the result Commented Sep 9, 2013 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. Commented Sep 9, 2013 at 17:31
  • 1
    format your string to be 9/30/2018 Commented Sep 9, 2013 at 17:35
  • I recommend using Moment.js. 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. Commented Sep 9, 2013 at 17:57
  • Possible duplicate of How to format a JavaScript date Commented Feb 19, 2016 at 21:46

2 Answers 2

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]]
Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

new Date(30, ..) will be off by two millennium!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.