Transform JSON time data from Coordinated Universal Time (UTC) to Indian Standard

Hello, I consider myself an amateur in the world of online javascript learning. Currently, I have come across a challenge that has left me stuck.

I am working with a JSON time data provided in UTC format (e.g. 16:00:00Z) and my goal is to convert it to 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
}

After doing some research online, I attempted adding the following:

mytime = mytime.toLocaleString();

Unfortunately, this only returns my local day, date, and time rather than the intended time from the JSON data. Any assistance on this matter would be greatly appreciated.

Answer №1

It has been noted in the comments that when the Date constructor is invoked as a function, it simply returns a string representing the current date and time, similar to calling new Date().toString().

There is no specific format known as "UTC format". UTC is actually a time standard, whereas the format you are likely referring to is ISO 8601.

The provided URL serves a JSON file containing the date and time in this structure:

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

Parsing strings using the built-in constructor can be tricky at times, as highlighted in this Stack Overflow thread: Why does Date.parse give incorrect results?.

However, if you wish to convert the date and time into a valid ISO 8601 timestamp, you can concatenate the components like so:

2022-04-10T05:00:00Z

This combined timestamp will be correctly parsed by the internal parser when used with the Date constructor, for example:

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}`;

Here's a snippet of code that you can run:

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 time
console.log(date.toString());
// Melbourne local time (also provided in the JSON)
console.log(date.toLocaleString('en-AU', {timeZone:'Australia/Melbourne', timeZoneName:'short'}));
// Indian time
console.log(date.toLocaleString('en-AU', {timeZone:'Asia/Kolkata', timeZoneName:'long'}));

Remember to declare your variables properly to avoid global scope issues or errors in strict mode.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue of Basic Bootstrap 5 Modal triggering twice is causing a frustrating experience

My modal is almost working perfectly - it changes content based on the clicked image, but it is triggering twice in the backend and I can't figure out why! I followed Bootstrap's documentation for this, so I'm unsure where the issue lies. Al ...

Troubleshooting problem with $http in AngularJS: encountering challenges with HTTP JSONP requests

I encountered the following error message while attempting to utilize the JSONP method in AngularJS: Uncaught SyntaxError: Unexpected token : http://example.com/getSomeJson?format=jsonp&json_callback=angular.callbacks._0 Could someone please ass ...

React: executing function before fetch completes

Whenever I trigger the ShowUserPanel() function, it also calls the getUsers function to retrieve the necessary data for populating the table in the var rows. However, when the ShowUserPanel function is initially called, the table appears empty without an ...

ng-repeat not functioning properly with FileReader

Here is a look at how my view appears: <body ng-controller="AdminCtrl"> <img ng-repeat="pic in pics" ng-src="{{pic}}" /> <form ng-submit="postPic()"> <input id="photos" type="file" accept="image/*" multiple/> <button> ...

To avoid any sudden movements on the page when adding elements to the DOM using jQuery, is there a way to prevent the page from

I have a challenge where I am moving a DIV from a hidden iFrame to the top of a page using jQuery. Here is my current code: $(document).ready(function($) { $('#precontainer').clone().insertBefore(parent.document.querySelectorAll(".maincontainer" ...

Issue adding dictionary value to an array in JavaScript

Let's analyze the code snippet below: var array = []; var obj = [{id: "xxxxx", name: "Friend name"}, {id: "xxxxx", name: "Friend name"}] for (x in obj){ array.push(x.name) } After running this code, the array ends up with the correct length but ...

Accessing XML files locally via JavaScript on Chrome or Internet Explorer, with compatiblity for Android mobile devices as well

Looking to extract and display data from an XML file directly in an HTML page without the need for a web server. Ready to dive into using JavaScript, jQuery, or Ajax to get the job done. ...

Having trouble getting your Bootstrap v4 carousel to function properly?

Currently, I have implemented the carousel feature from Bootstrap v4 in a Vue web application. I am following the same structure as shown in the sample example provided by Bootstrap, but unfortunately, it is not functioning correctly on my local setup and ...

Utilizing jQuery to Perform Calculations with Objects

Can someone help me with a calculation issue? I need to calculate the number of adults based on a set price. The problem I'm facing is that when I change the selection in one of the dropdown menus, the calculation doesn't update and continues to ...

What are the applications of global variables in node.js?

global.test = "test"; console.log(global.test); //test but I want to accomplish this: console.log(test); //test without using: var test = global.test; Is there a way to achieve this? I am looking for a solution where any module in my project does not ...

Assigning array materials in ThreeJS allows you to create complex

When I assign framemat to createScene(ID, geometry, 1, framemat), everything works fine. But when I try createScene( ID, geometry, 1, materials[ID] ), it doesn't cooperate. var jsonLoader = new THREE.JSONLoader(), paths = [ "obj/jgd/ ...

Having trouble extracting the video ID from a Youtube feed XML with jQuery

My goal here is quite simple - I have created a search result using a URL string with the YouTube API. When you visit the URL, you can view the XML returned without any issues. The specific URL is: https://gdata.youtube.com/feeds/api/videos?q=all the smal ...

Prevent the ability to drag and drop within specific div elements

Having trouble disabling the sortable function when the ui ID is set to "comp". Can't figure out what's going wrong, hoping for some assistance here. $(".sort").sortable({ // start sortable connectWith: ".sort", receive: function ...

The issue of infinite rendering caused by useState and how to effectively resolve it

I'm facing a strange issue in just a few lines of code, and I can't quite figure out what's happening behind the scenes. Here are the 4 lines causing trouble: function FarmerComponent(props) { let authCtx = useContext(AuthContext) let u ...

Three.js dynamic bone animation: bringing your project to life

Can transformations be applied to the bones of a 3D model in three.js to create a dynamic animation? I attempted to move and rotate the bones of a SkinnedMesh, but the mesh did not update. loader = new THREE.JSONLoader(); loader.load(&apos ...

"Enhance your database by incorporating HTML link clicks through AJAX integration with PHP and MySQL

After browsing through similar questions and attempting to implement it on my website, I'm facing an issue where the expected functionality is not working as intended. When users click on a link, there is no response in the console, and the database r ...

How come the method $.when().pipe().then() is functioning properly while $.when().then().then() is not working as expected

I'm still grappling with the concept of using JQuery's Deferred objects, and am faced with a puzzling issue. In this code snippet, my attempt to chain deferred.then() was unsuccessful as all three functions executed simultaneously. It wasn't ...

Is there a way to locate the source or URL linked to a button on a form or webpage?

Currently, I am extracting data feeds from a webpage by clicking a button that is similar to the 'Login' button displayed on the following link: However, this button acts as a 'Download' request that initiates the download of a csv rep ...

How come TypeScript remains silent when it comes to interface violations caused by Object.create?

type Foo = { x: number; }; function g(): Foo { return {}; // Fails type-check // Property 'x' is missing in type '{}' but required in type 'Foo'. } function f(): Foo { return Object.create({}); // Passes! } functio ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...