2 回答
TA贡献1783条经验 获得超5个赞
您的日期似乎是 的标准字符串表示new Date(),您可以使用new Date().toISOString()
console.log(new Date().toString())
console.log(new Date().toISOString())
// To create it from string
const dateStr = "Fri Apr 20 2020 00:00:00 GMT+0530 (India Standard Time)"
console.log(new Date(dateStr).toISOString())
TA贡献1797条经验 获得超6个赞
Anurag Srivastava 的回答显示了您应该如何解析字符串并将其格式化为所需的格式(假设字符串是 ECMA-262 支持的两种格式之一,并考虑为什么 Date.parse 给出不正确的结果?)。
请注意,“Fri Apr 20 2020 00:00:00 GMT+0530(印度标准时间)”与“2020-04-19T18:30:00.000Z”的时间相同。第一个字符串从 UTC 偏移 5 小时 30 分钟,因此等效的 UTC 时间提前 5 小时 30 分钟,这意味着日期是前一天。
您还没有给出为什么要将其视为 UTC 并且不考虑偏移量的原因,所以我认为您不应该这样做。
但是,如果您确实有充分的理由将其解析为 UTC 并忽略提供的偏移量,那么您可以:
修改输入字符串以将偏移量设置为 +0 并使用内置解析器对其进行解析
自己解析字符串并将其视为 UTC
let s = "Fri Apr 20 2020 00:00:00 GMT+0530 (India Standard Time)";
// #1 Modify the input string, setting the offset to +0
let d = new Date(s.replace(/GMT.*$/,'GMT+0000')).toISOString();
console.log(d.toISOString());
// #2 Bespoke parser
function parseAsUTC(s) {
let months = ['jan','feb','mar','apr','may','jun',
'jul','aug','sep','oct','nov','dec'];
let b = s.split(/\W/);
return new Date(Date.UTC(b[3], months.indexOf(b[1].toLowerCase()),
b[2], b[4], b[5], b[6]));
}
console.log(parseAsUTC(s).toISOString());
添加回答
举报
