To convert a 24-hour UTC time to local time in JavaScript, you can use the built-in Date object and its methods. Here’s an example:

// Example input: 24-hour UTC time in format "HH:mm:ss"
var utcTime = "14:30:00";

// Create a new Date object with the UTC time
var date = new Date("2000-01-01T" + utcTime + "Z");

// Get the local time by converting the UTC time to the local time zone
var localTime = date.toLocaleTimeString([], { hour12: false });

console.log(localTime);

In this example, we assume that the input is a string representing the time in the “HH:mm:ss” format. You can replace the utcTime variable with your own UTC time string.

The code creates a new Date object using the provided UTC time and sets the date to January 1, 2000 (it’s just an arbitrary date used to perform the conversion). The “Z” at the end of the UTC time string indicates that it is in UTC format.

Then, the toLocaleTimeString method is called on the date object to convert the UTC time to the local time zone. The { hour12: false } option is passed to display the time in the 24-hour format without AM/PM indicators.

Finally, the local time is logged to the console. You can modify the code to store or display the local time in any way you need.

Thanks for reading

Leave a Reply

Your email address will not be published. Required fields are marked *