0

I have strings that are supposed to be dates in the following format: 01.02.19 (this would be 01 February 2019)

I am trying to convert these string to real dates, so I am doing the following:

var parts ='01.02.19'.split('.');

var mydate = new Date(parts[0], parts[1], parts[2]); 

The result from the above is Mar 18 1901 while it should be Feb 01 2018.

What am I doing wrong?

2
  • javascript month is zero based. 0 = Jan 1 = Feb etc. Commented Mar 4, 2019 at 14:59
  • 3
    see MDN docs for example, this should be new Date(year, monthIndex, day);, note also that 19 is 1919.. Commented Mar 4, 2019 at 14:59

3 Answers 3

1

The Date constructor takes the largest to smallest times, so it starts with year. The year needs to be the full four digits and months are zero-indexed so February would be month 1.

To fix your issue, swap the parts, decrease parts[1] by 1 and prefix parts[2] with 20

var parts ='01.02.19'.split('.');
var date = new Date("20" + parts[2], parts[1] - 1, parts[0]);

console.log(date.toGMTString());

Sign up to request clarification or add additional context in comments.

Comments

1

If including the wonderful MomentJS is an option, you can do :

moment("01.02.19", "DD.MM.YY").format("MMM DD YYYY") // Feb 01 2019

1 Comment

I'm never a fan of including a JS library for a single feature, but I'll admit that MomentJS' date parsing is pretty sweet
0

You can use the following array to extract the month name also changing the order of parts in new Date like this:

new Date(`${parts[1]}/${parts[0]}/${parts[2]}`);  

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

var parts ='01.02.19'.split('.');

var mydate = new Date(`${parts[1]}/${parts[0]}/${parts[2]}`); 

console.log(` ${monthNames[mydate.getMonth()] } ${mydate.getDate()} ${mydate.getFullYear()}`)

Comments

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.