简体   繁体   English

javascript一致的日期格式

[英]javascript consistent format of date

I have a function that is expecting the startDate and endDate to be in YYYY-mm-dd format as a (String).我有一个函数,它期望 startDate 和 endDate 采用 YYYY-mm-dd 格式作为(字符串)。 Because I'm using a couple components/plugins, sometimes the dates are coming in different formats.因为我使用了几个组件/插件,有时日期会以不同的格式出现。

If the date comes in as "Wed Jan 01 2020 00:00:00 GMT-0800" format.如果日期是“Wed Jan 01 2020 00:00:00 GMT-0800”格式。 I want to convert it into YYYY-mm-dd However, if its already in YYYY-mm-dd format, don't touch it.我想把它转换成 YYYY-mm-dd 但是,如果它已经是 YYYY-mm-dd 格式,不要碰它。

I tried using something like where I pass in my initial string, but it seems to be messing up my date because of the inconsistent nature of the startDate value.我尝试使用类似我传入初始字符串的地方,但由于 startDate 值的不一致性质,它似乎弄乱了我的日期。

var d = new Date(startDate);

var datestring = d.getDate()  + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();

You can easily achive the data in YYYY-mm-dd format using toISOString and split您可以使用toISOStringsplit轻松获得YYYY-mm-dd格式的数据

 function getDate(date) { return date.match(/^\\d{4}-\\d{2}-\\d{2}$/) ? date : new Date(date).toISOString().split("T")[0]; } console.log(getDate("2020-03-12")); console.log(getDate("Wed Jan 01 2020 00:00:00 GMT-0800")); console.log(getDate("Wed Dec 01 2020 00:00:00 GMT-0800")); console.log(getDate("Wed Mar 29 2020 00:00:00 GMT-0800"));

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

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