[英]How to convert ISO 8601 Date+Time strings from Firebase to `Date` values in JavaScript?
I have this firebase Timestamp dates:我有这个 firebase 时间戳日期:
time1: "2021-02-19T15:23:47.747Z"
time2: "2021-02-19T15:28:04.331Z"
and I need to convert these dates to normal dates.我需要将这些日期转换为正常日期。 I want to do this in Javascript.
我想在 Javascript 中执行此操作。 How can I do this?
我怎样才能做到这一点?
You can get ms timestamp with:您可以通过以下方式获取 ms 时间戳:
new Date(time1).getTime()
You should use Date.parse()
to convert your string to milliseconds.您应该使用
Date.parse()
将您的字符串转换为毫秒。 You can then convert that into whatever you need.然后,您可以将其转换为您需要的任何内容。
const time1 = convertTimestamp("2021-02-19T15:23:47.747Z"); const time2 = convertTimestamp("2021-02-19T15:28:04.331Z"); function convertTimestamp(dateStr) { const start = Date.parse(dateStr); let now = new Date(0); // The 0 is important now.setUTCMilliseconds(start); const output = now.getUTCFullYear() +"/"+ (now.getUTCMonth()+1) +"/"+ now.getUTCDate() + " " + now.getUTCHours() + ":" + now.getUTCMinutes(); document.body.append(output + ' '); return output; }
Avoid the new Date(dateString)
format as it doesn't have consistent behavior over different environments.避免使用
new Date(dateString)
格式,因为它在不同环境中的行为不一致。
You can convert it like that:你可以像这样转换它:
new Date('2021-02-19T15:23:47.747Z').toGMTString().split(' ')
// ["Fri,", "19", "Feb", "2021", "15:23:47", "GMT"]
Or或者
let converted = new Date('2021-02-19T15:23:47.747Z').toGMTString().split(' ');
let date = {
year: converted[3],
month: converted[2],
day: converted[1],
time: converted[4],
timezone: converted[5]
}
// day: "19"
// month: "Feb"
// time: "15:23:47"
// timezone: "GMT"
// year: "2021"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.