![](/img/trans.png)
[英]How to convert an ISO 8601 date to '/Date(1525687010053)/' format in javascript?
[英]How to convert ISO 8601 Date+Time strings from Firebase to `Date` values in JavaScript?
我有這個 firebase 時間戳日期:
time1: "2021-02-19T15:23:47.747Z"
time2: "2021-02-19T15:28:04.331Z"
我需要將這些日期轉換為正常日期。 我想在 Javascript 中執行此操作。 我怎樣才能做到這一點?
您可以通過以下方式獲取 ms 時間戳:
new Date(time1).getTime()
您應該使用Date.parse()
將您的字符串轉換為毫秒。 然后,您可以將其轉換為您需要的任何內容。
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; }
避免使用new Date(dateString)
格式,因為它在不同環境中的行為不一致。
你可以像這樣轉換它:
new Date('2021-02-19T15:23:47.747Z').toGMTString().split(' ')
// ["Fri,", "19", "Feb", "2021", "15:23:47", "GMT"]
或者
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.