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

Change classes of sibling elements using Angular 2

Imagine you have the following code snippet: <div id="parent"> <div class="child"> <div class="child"> <div class="child"> </div> I am looking to automatically assign the class active to the first child element. ...

Eliminating duplicate data submissions with jQuery Ajax

Encountering an issue with my jQuery AJAX submission process. JavaScript: $('#myform').submit(function () { if (validateEvenInputs()) { $('#btnevent').attr('disabled', 'disabled'); function ...

Issues with removing options from Autocomplete persist in React MaterialUI

Currently navigating the world of ReactJS and experimenting with Material UI's Autocomplete component. The challenge lies in managing a complex data structure where options are dynamically generated based on user selections, but removing previously se ...

Trouble with mapping an array in my Next JS application

When working on my Next JS app, I encountered an error while trying to map an array for the nav bar. The error message reads: TypeError: _utils_navigation__WEBPACK_IMPORTED_MODULE_6___default(...).map is not a function. Here is the code snippet that trigge ...

Tips for integrating TypeScript with Vue.js and Single File Components

After extensive searching online, I have struggled to find a straightforward and up-to-date example of setting up Vue.js with TypeScript. The typical tutorials out there either are outdated or rely on specific configurations that don't apply universal ...

Guide to obtaining ngPrime autocomplete text when the button is clicked within Angular 6

I am currently utilizing the ngPrime autocomplete feature to retrieve data from a service. My goal is to capture the text entered in the autocomplete field whenever a button is clicked. I attempted to access the value using getElementById.value within th ...

Encountered a problem while parsing an XML file using JavaScript from an external server

Currently, I am developing an iPhone application in HTML that needs to pull content from an XML file stored on a remote server and display it in a list. I have successfully accomplished this task when the XML file is hosted on the same server using the fo ...

Updating data in Redux triggers a refresh of Material UI table data

Utilizing the material-ui data table component to showcase data, enabling users to update and save information via a form when clicking on a row. Implemented react-redux for state management and dispatching updated rows to the existing data. However, despi ...

Executing JavaScript - Triggering an 'onClick' event within a For loop to dynamically load multiple hyperlinks

I am currently working on creating a listview using JSON data. However, when I call an 'onclick' function from a For loop, the link opens in a new window and loads three URLs into the browser's URL input. Is there a way to modify the code be ...

OpenLayers: real-time data display of objects from a list

When working with OpenLayers, I encountered an issue where my object was undefined and I couldn't retrieve the information I needed to display feature data on the map. Initially, I passed a list from the controller to my JSP file and attempted to use ...

Using an external module in a Vue SFC: a beginner's guide

Recently delving into Vue, I'm working on constructing an app that incorporates Typescript and the vue-property-decorator. Venturing into using external modules within a Single File Component (SFC), my aim is to design a calendar component utilizing t ...

What is it about Next JS and React JS applications that causes them to use up so much cache?

"What causes Next.js and React.js applications to need a large cache, and how does this affect their performance and resource usage?" Refreshing constantly for even small changes in the application as a developer can be frustrating. Are there an ...

Is there a way for me to streamline the process of logging in using either Google or Facebook?

Is there a way for me to automate the scenario if I'm unable to locate the element using Appium Uiautomator? https://i.stack.imgur.com/Rjji4.png ...

JavaScript: Unusual behavior discovered in forEach iteration

Here's the code snippet I'm having trouble with: someArray.forEach(x => { // do something console.log(‘calling api for ‘ + x); callAnHttpApiAsync(...); sleep(10); }); The issue lies in the asynchronous nature of the HTTP API call within ...

What are the steps to manipulate the data within an EJS file after passing an array through Node.js as an object?

I'm currently developing a simple calendar application using Node.js and ejs. I am working on passing an array of months through express to my ejs file, with the goal of being able to cycle through each month by clicking the next button. How can I imp ...

Creating a weekly year pivot table in pandas

I'm a beginner with pandas and I need to create pivot tables for each week using data from a csv file that contains records spanning multiple years. I am having trouble figuring out the best way to filter the dataframe by week. Currently, I am doing ...

Exploring the world of Node.js, JSON, SQL, and database tables

Hello everyone, I have been working on a project using Node.js and Express framework. My current goal is to create a client-side page that allows users to input form data into a MySQL database. I have managed to successfully insert and retrieve data from ...

javascript code for subtracting values in arrays

I am facing a scenario where I have 3 arrays of the same length. My requirement is to automatically subtract the values in the first two arrays without any user input. If the result of subtraction is negative, I need to identify the index of that array num ...

What steps can I take to prevent my menu items from overlapping in the mobile navigation menu?

I am currently working on creating a mobile menu, but I'm facing an issue where the menu items overlap when hovered over. Instead, I want the menu items to move downwards when hovered upon to prevent the text from overlapping. Below is the HTML code ...

The background image causes the scrollbar to vanish

As a beginner, I am in the process of creating a web page that features a consistent background image. However, I have encountered an issue where the scroll bar does not appear on a specific page called "family details" due to the background image. I atte ...