简体   繁体   English

javascript中的字符串到日期格式

[英]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) 我的字符串应该是以下格式的日期: 01.02.19 (这将是2019年2月1日)

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. 上面的结果是1901年3月18日,应该是2018年2月1日。

What am I doing wrong? 我究竟做错了什么?

The Date constructor takes the largest to smallest times, so it starts with year. Date构造函数使用最大到最小的时间,因此从年份开始。 The year needs to be the full four digits and months are zero-indexed so February would be month 1 . 年份必须是完整的四位数,并且月份是零索引,因此2月将是月份1

To fix your issue, swap the parts, decrease parts[1] by 1 and prefix parts[2] with 20 要解决您的问题,请交换零件,将parts[1]减少1并在parts[2]加上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: 您可以使用以下数组提取月份名称,也可以像这样更改新Date中零件的顺序:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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