将Json的时间从UTC转换为IST



所以我是一个业余爱好者,正在学习在线javascript,但现在我被我正在尝试的东西卡住了。

我正在从json中获得UTC格式的时间(例如16:00:00Z(,并希望获得IST。

var main = function () {
json_url = "http://ergast.com/api/f1/current/next.json";
xhr = new XMLHttpRequest();
xhr.open("GET", json_url, false);
xhr.send(null);
weather = JSON.parse(xhr.responseText);
mydate = weather.MRData.RaceTable.Races[0].Qualifying.time;
mytime = Date(mydate);
mytime = mytime.toLocaleString();
return mytime
}

根据我在网上的了解,我尝试添加

mytime = mytime.toLocaleString();

但这会返回我的本地日期、日期和时间,而不是我想要的json中的时间。任何帮助都将不胜感激。

正如注释中所指出的,作为函数调用的Date构造函数只返回当前日期和时间的字符串,就好像调用了new Date().toString()一样。

不存在";UTC格式";。UTC是一个时间标准,您正在寻找的是ISO 8601。

URL返回一个JSON文件,日期和时间如下:

"date":"2022-04-10",
"time":"05:00:00Z"

使用内置构造函数分析字符串有些问题,请参阅为什么Date.parse给出不正确的结果

但是,要将日期和时间转换为date,您可以将这些部分连接起来,形成一个有效的ISO 8601时间戳,如:

2022-04-10T05:00:00Z

将由内置解析器使用Date构造函数正确解析,例如

let date = weather.MRData.RaceTable.Races[0].Qualifying.date;
let time = weather.MRData.RaceTable.Races[0].Qualifying.time;
let mydate = new Date(`${date}T${time}`;

作为可运行的片段:

let obj = {"date":"2022-04-10", "time":"05:00:00Z"};
let date = new Date(`${obj.date}T${obj.time}`);
// UTC 
console.log(date.toISOString());
// Local to host
console.log(date.toString());
// In Australia/Melbourne (also contained in the JSON)
console.log(date.toLocaleString('en-AU', {timeZone:'Australia/Melbourne', timeZoneName:'short'}));
// In India
console.log(date.toLocaleString('en-AU', {timeZone:'Asia/Kolkata', timeZoneName:'long'}));

不要忘记声明变量,否则它们将变为全局变量(或者在严格模式下抛出错误(。

最新更新