gpt4 book ai didi

javascript - 如何将 "nd","rd", "th"的日期转换为 yyyy-mm-dd 格式的 Javasciript

转载 作者:行者123 更新时间:2023-12-01 03:31:20 26 4
gpt4 key购买 nike

我有一组日期,例如:

dates=['2nd Oct 2014','20th Oct 2014','20th May 2019']

我想将它们作为 YYYY-MM-DD 格式的数组返回。到目前为止我有这个:

function formatDate(dates) {
var t=[];
dates.map(function(date){
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();

if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
t.push([year, month, day].join('-'));
});
console.log(t);


return t;
}
var dates = ['2nd Oct 2014','20th Oct 2014','20th May 2019']
console.log(formatDate(dates));

但这给了我:

[NaN-NaN-NaN,NaN-NaN-NaN,NaN-NaN-NaN]

因为它无法识别带有“th”、“nd”的日期。知道如何解决这个问题以便我得到 o/p 为:

[2014-10-02,2014-10-20,2019-05-20]

这是 fiddle :http://jsfiddle.net/nakpchvf/

谢谢!

最佳答案

如果您使用 moment ,或者如果使用它是一个选项,它相当简单:

const dates=['2nd Oct 2014','20th Oct 2014','20th May 2019'];

dates.forEach(date => {
console.log(moment(date, 'Do MMM YYYY').format('YYYY-MM-DD'));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>

关于javascript - 如何将 "nd","rd", "th"的日期转换为 yyyy-mm-dd 格式的 Javasciript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54047914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com