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.
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:
"date":"2022-04-10",
"time":"05:00:00Z"
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:
2022-04-10T05:00:00Z
that will be parsed correctly by the built–in parser using the Date constructor, e.g.
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}`;
As a runnable snippet:
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'}));
Don't forget to declare variables, otherwise they'll become global (or throw an error in strict mode).