简体   繁体   中英

String to date format in javascript

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?

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

如果可以选择包含精彩的MomentJS,则可以执行以下操作:

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

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()}`) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM