Convert Date String(yymmdd) to Date Object in JS

偶尔善良 提交于 2019-12-25 08:29:25

问题


I have a date string in "yymmdd" format i want to convert it into date object in JS the input string is "161208" I have tried code below

var mydate = new Date(InputDate);

but it says invalid date. Here is the fiddle https://jsfiddle.net/4ry0hL4t/

the basic need is that, I have a date string in "yymmdd" format and i have to convert it to different date formats like ("yyyy/mm/dd, yy-mm-dd","yy/mm").


回答1:


Check my answer. Basically you first need to give a proper format to your string. You can either do it manually or use moment.js.

stringFormat = moment(dateObject).format("YYYY-MM-DDTHH:mm:ss");
date = new Date(stringFormat);

This is also really helpful to understand how the different string formats are compatible with different browsers.




回答2:


I'm not sure if this is what you're after?

var s = '161208';
var dt = new Date('20' + s.substring(0, 2) + '-' + s.substring(2, 4) + '-' + s.substring(4));


来源:https://stackoverflow.com/questions/41122493/convert-date-stringyymmdd-to-date-object-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!