-2

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.

pilchard
  • 12,414
  • 5
  • 11
  • 23
KICK1O1
  • 11
  • 1
  • Why do you use this line `mytime = Date(mydate);`? `Date` as function doesn't expect any arguments and is equivalent to `new Date().toString()`. – jabaa Mar 27 '22 at 20:06
  • 1
    That would be to create a [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) from the string retrieved from the JSON response, but obviously should be `new Date(mydate)` (possible parsing problems here). – pilchard Mar 27 '22 at 20:07
  • 1
    The conversion from one timezone to another depends on the date. There are leap seconds and daylight saving times. – jabaa Mar 27 '22 at 20:10

1 Answers1

0

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).

RobG
  • 142,382
  • 31
  • 172
  • 209