【发布时间】:2023-03-09 09:02:01
【问题描述】:
假设我们在 2020 年 1 月 1 日午夜在伦敦,并进入一个应用程序,该应用程序将日期时间存储为这样的 ISO-8601 字符串。2020-01-01T00:00:00-00:00
稍后,我在洛杉矶,想在需要 javascript 日期对象的图表上查看此日期。
获取本地化的日期对象很容易。
const iso8601Date = '2020-01-01T00:00:00+00:00';
const theDate = new Date(iso8601Date);
console.log(typeOf(theDate)); // date
console.log(theDate); // Tue Dec 31 2019 16:00:00 GMT-0800 (PST)
但是,有时我们想“忽略”时区偏移并分析数据,就好像它发生在当前时区一样。
这是我正在寻找但不知道如何完成的结果。
const iso8601Date = '2020-01-01T00:00:00+00:00';
const theRepositionedDate = someMagic(iso8601Date);
console.log(typeOf(theRepositionedDate)); // date
console.log(theRepositionedDate); // Wed Jan 01 2020 00:00:00 GMT-0800 (PST)
如何重新定位日期并返回一个日期对象?
/* Helper function
Returns the object type
https://stackoverflow.com/a/28475133/25197
typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
*/
function typeOf(obj) {
return {}.toString
.call(obj)
.split(' ')[1]
.slice(0, -1)
.toLowerCase();
}
【问题讨论】:
标签: javascript datetime