将 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();
But 这会返回我的本地日期、日期和时间,而不是我想要的 json 中的时间。任何帮助将不胜感激。
So I’m a amateur and being learning online javascript but now I’m stuck on something I’m trying.
I’m getting a time from json in UTC format (eg. 16:00:00Z) and want to get in 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
}
From what I understood online I tried adding
mytime = mytime.toLocaleString();
But that returns my local day, date and time and not time from json as I intended. Any help will be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如注释中所指出的,作为函数调用的 Date 构造函数仅返回当前日期和时间的字符串,就像调用 new Date().toString() 一样。
没有“UTC 格式”。 UTC 是一种时间标准,您要查找的标准是 ISO 8601。
URL 返回一个 JSON 文件,其日期和时间如下:
使用内置构造函数解析字符串有些问题,请参阅 为什么 Date.parse 给出不正确的结果?。
但是,要将日期和时间转换为 Date,您可以连接各个部分以形成有效的 ISO 8601 时间戳,例如:
内置解析器将使用 Date 构造函数正确解析该时间戳,例如
As可运行的片段:
不要忘记声明变量,否则它们将成为全局变量(或在严格模式下抛出错误)。
As pointed out in comments, the Date constructor called as a function just returns a string for the current date and time as if
new Date().toString()
was called.There is no "UTC format". UTC is a time standard, the one you're looking for is ISO 8601.
The URL returns a JSON file with the date and time as:
Parsing strings with the built–in constructor is somewhat problematic, see Why does Date.parse give incorrect results?.
However, to turn the date and time into a Date you can concatenate the parts to form a valid ISO 8601 timestamp like:
that will be parsed correctly by the built–in parser using the Date constructor, e.g.
As a runnable snippet:
Don't forget to declare variables, otherwise they'll become global (or throw an error in strict mode).