我有一个元素为
的数组var getDaysArray = [
"2021-10-28T08:00:00",
"2021-10-27T08:00:00",
"2021-10-31T03:00:00"
]
我需要得到以下结果MM/DD/YYYY - HH:MM PM太平洋时间
我可以替换"-">与"/">使用replace
for(var i = 0; i < getDaysArray.length; i++) {
document.write(getDaysArray[i].replace("-", "/"));
}
但是我需要得到以下结果
10/28/2021 - 19:25
将输入字符串解析为日期,并使用适当的选项集转换为所需的区域设置字符串:
const datesArray = [
"2021-10-28T08:00:00",
"2021-10-27T08:00:00",
"2021-10-31T03:00:00"
],
translateDateStr = dateStr => {
const [yyyy, mm, dd, hh, mi, ss] = dateStr.split(/[-T:]/)
const date = new Date(Date.UTC(yyyy, mm-1, dd, hh, mi, ss))
return date
.toLocaleString(
'en-US',
{
timeZone: 'America/Los_Angeles',
hour12: false
}
)
.slice(0,-3)
.replace(', ', ' - ')
},
formattedDates = datesArray.map(translateDateStr)
console.log(formattedDates)
.as-console-wrapper{min-height:100%}
如果不使用像momentjs这样的外部库,您将不得不重新格式化每个数组元素并将它们推入新数组。
let formattedDays = [];
for(i = 0; i < getDaysArray.length; i++) {
const date = new Date(getDaysArray[i]);
const month = date.getMonth()+1; //months go from 0-11
const day = date.getDate();
const year = date.getFullYear();
const hour = date.getHours();
const minutes = date.getMinutes();
const dateString = month+"/"+date+"/"+year+" - "+hour+":"+minutes
formattedDays.push(dateString);
}
console.log(formattedDays);
你必须使用moment.js来解决这个问题。您的代码可能看起来像以下代码
var getDaysArray = [
"2021-10-28T08:00:00",
"2021-10-27T08:00:00",
"2021-10-31T03:00:00"
]
getDaysArray.forEach(x=>{
console.log(moment(Date.parse(x), 'DD.MM.YYYY HH:mm:ss'));
})