猿问

在反应中将多个日期拆分为特定格式

我想转换这么多日期

2019 年 11 月 13 日星期三 00:00:00 GMT+0000 (UTC),2019 年 11 月 19 日星期二 00:00:00 GMT+0000 (UTC),2019 年 11 月 19 日星期二 00:00:00 GMT+0000 (UTC)

11/13/2019,11/19/2019,11/19/2019


红颜莎娜
浏览 155回答 3
3回答

慕桂英546537

既然你标记了你的问题momentjs,这里有一个使用 moment JS 库的解决方案。首先你拆分你的字符串,然后你格式化每个日期,最后你加入字符串。注意:这会给你一个警告,因为初始日期格式不是标准化的。const dates = 'Wed Nov 13 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC)'const parseDates = dates => (&nbsp; dates&nbsp; .split(',')&nbsp; .filter(date => moment(date).isValid())&nbsp; .map(date => moment(date).format('MM/DD/YYYY'))&nbsp; .join(','))console.log(parseDates(dates));<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>否则,如果您确定您的日期将始终具有相同的格式,您可以使用正则表达式手动解析它们:const months = [ '', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']const dateRegex = /[\w]{3}\s{1}([\w]{3})\s{1}(\d{2})\s{1}(\d{0,4})\s/iconst dates = 'Wed Nov 13 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC)'const parseDatesFallback = dates => (&nbsp; dates&nbsp; .split(',')&nbsp; .map(date => {&nbsp; &nbsp; date = date.match(dateRegex)&nbsp; &nbsp; return String(months.indexOf(date[1])).padStart(2, '0')&nbsp;&nbsp; &nbsp; &nbsp; + '/'&nbsp; &nbsp; &nbsp; + date[2]&nbsp; &nbsp; &nbsp; + '/'&nbsp; &nbsp; &nbsp; + date[3]&nbsp; })&nbsp; .join(','))console.log(parseDatesFallback(dates));

神不在的星期二

您可以简单地将日期列表映射到所需的日期格式。使用splitandjoin方法将字符串转换为数组并返回。例子:const dates = 'Wed Nov 13 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC)';const newDates = dates.split(',')&nbsp; .map(dateString => {&nbsp; &nbsp; const date = new Date(dateString);&nbsp; &nbsp; return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;&nbsp; })&nbsp; .join(',');console.log(newDates);

largeQ

const str = 'Wed Nov 13 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC),Tue Nov 19 2019 00:00:00 GMT+0000 (UTC)'const arr = str.split(',').map(a=>moment(a).format('MM/DD/YYYY'));console.log(arr)<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.min.js" type="text/javascript"></script>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答