How to change timezone without changing date value

Forums JavaScriptHow to change timezone without changing date value
Staff asked 2 years ago

Answers (1)

Add Answer
Umang Ramani Marked As Accepted
Staff answered 2 years ago

To change the timezone of a date without changing its value in JavaScript, you can use the toLocaleString() method in combination with the timeZone option. Here’s an example:

// Create a date object with the current date and time
const date = new Date();

// Get the current timezone offset in minutes
const timezoneOffset = date.getTimezoneOffset();

// Convert the date to a string with the desired timezone
const dateString = date.toLocaleString('en-US', { timeZone: 'America/New_York' });

// Parse the string back into a date object with the same value as the original date
const newDate = new Date(dateString);

// Verify that the new date has the same value as the original date
console.log(date.getTime() === newDate.getTime()); // true

Here, the date variable is initialized with the current date and time. The getTimezoneOffset() method is called on the date object to get the current timezone offset in minutes. This value is then used to convert the date to a string with the toLocaleString() method, passing in the timeZone option with the desired timezone (in this case, America/New_York). Finally, the resulting string is parsed back into a date object with the Date() constructor, creating a new date object with the same value as the original date but with the desired timezone.

Note that the toLocaleString() method will format the date and time according to the locale of the user’s system, so the resulting string may have a different format depending on the user’s location.

Subscribe

Select Categories