Javascript convert to timezone

How to convert the local time to another timezone in JavaScript

While you are working with date time in project then you might need to convert the local time to another timezone using JavaScript or you need to convert a UTC time to another timezone. So today we will show you how to convert the local time to another timezone in JavaScript.

Checkout more articles on JavaScript

Steps to convert local time to another timezone

1. Get current local time in milliseconds

Using a new Date() object we can get the current date time in the local timezone and we have to convert it into the milliseconds.

var date = new Date(); var localTime = date.getTime();

2. Find the local timezone offset

Using getTimezoneOffset() method we can find the local timezone offset. By default this method returns the timezone offset in minutes, so let’s convert this value into milliseconds for further process.

// get local timezone offset and convert to milliseconds var localOffset = date.getTimezoneOffset() * 60000;

3. Obtain the current UTC time

To get the current UTC time, we have to add the local timezone offset to the local time.

// obtain the UTC time in milliseconds var utc = localTime + localOffset;

4. Get destination city’s UTC offset in hours

Move forward to get the destination city’s UTC offset, first get destination city’s offset (For example, we are considering the destination city as Ahmedabad which is 5.5 hours). Now convert it to the milliseconds and add it to the UTC time.

var offset = 5.5; // offset for Ahmedabad is 5.5 hours var ahmedabadDateTime = utc + (3600000 * offset);

5. Get date of another timezone in readable datetime

Now, we can get the date of another timezone in readable format using new Date() object and call the toLocaleString() method.

var convertedDateTime = new Date(ahmedabadDateTime); convertedDateTime.toLocaleString(); // Local time in Ahmedabad

Example:

Let’s combine all the steps together and create function which can return the local time of the destination city by passing the offset of destination city as parameter.

function calculateDateTime(offset) < // get current local time in milliseconds var date = new Date(); var localTime = date.getTime(); // get local timezone offset and convert to milliseconds var localOffset = date.getTimezoneOffset() * 60000; // obtain the UTC time in milliseconds var utc = localTime + localOffset; var newDateTime = utc + (3600000 * offset); var convertedDateTime = new Date(newDateTime); return convertedDateTime.toLocaleString(); >// get Bombay time console.log(calculateDateTime(5.5)); // get Arizona time console.log(calculateDateTime(-7));

I hope you find this article helpful.
Thank you for reading. Happy Coding.

You Might Also Like

Disable the resizing of the textarea element

Disable the resizing of the textarea element

How to Scroll to an Element using JavaScript

September 7, 2022

How to Scroll to an Element using JavaScript

JavaScript Window Navigator Object

December 4, 2022

Источник

Convert a Date to Another TimeZone Using JavaScript

A time zone belongs to the region that follows a standard local time recognized by law throughout the nation. Some countries have their own time zone, and some countries, such as the United States or Canada, even have several time zones. On a web page, developers may need to convert dates from one time zone to any other specified time zone for different purposes.

This post will describe the method for converting a date to any other specified time zone using JavaScript.

How to Convert a Date to Another Specified Time Zone Using JavaScript?

To convert a date to another timezone, use the given methods:

Let’s discuss these methods in detail!

Method 1: Convert a Date to Another Time Zone Using toLocaleString() Method

For converting the date to any specified time zone, use the “toLocaleString()” method. It will change the date from one timezone to another. The toLocaleString() method returns a string that converts the date based on the locale and parameters passed in.

Follow the given syntax for the “toLocaleString()” method to convert the date to another timezone:

First, create a new date object using the Date() constructor that returns the current date, and stores it in a variable “date”:

Print the current date on the console:

Call the “toLocaleString()” method to convert the date to “America/New_York” timezone and store the resultant date and time in variable “timeZoneUSA”:

Print the resultant date in the “America/New_York” timezone on the console:

The output indicates that the date is successfully converted to the specified timeZone:

Method 2: Convert a Date to Another Time Zone Using format() Method

Another way to convert the date to another time zone is the “format()” method. It converts one time zone to another.

The following syntax is used for the format() method:

First, call the “Intl.DateTimeFormat” object to set the timezone in which the date will be converted into that timezone as it enables language-sensitive date and time formatting. Here, we will convert the date to the “America/New_York” timezone:

Then, call the format() method with the specified timezone and “date” as a parameter:

Print the resultant converted timezone on the console:

We have gathered all the necessary information related to the conversion of a Date object to another timezone in JavaScript.

Conclusion

For conversion of Date to any other timezone, use the “toLocaleString()” method or the “format()” method. Both methods return the string of the date into the specified timezone. This post described the methods for converting the current date to any other specified time zone using JavaScript.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Javascript convert to timezone

Last updated: Jan 12, 2023
Reading time · 4 min

banner

# Convert a Date to another Time Zone using JavaScript

To convert a date to another time zone:

  1. Use the toLocaleString() method to get a string that represents the date according to the provided time zone.
  2. Pass the result to the Date() constructor.
  3. The returned Date object will have its date and time set according to the provided time zone.
Copied!
function changeTimeZone(date, timeZone) if (typeof date === 'string') return new Date( new Date(date).toLocaleString('en-US', timeZone, >), ); > return new Date( date.toLocaleString('en-US', timeZone, >), ); > const laDate = changeTimeZone(new Date(), 'America/Los_Angeles'); console.log(laDate); // 👉️ "Sun Jan 16 2022 01:22:07" const berlinDate = changeTimeZone(new Date(), 'Europe/Berlin'); console.log(berlinDate); // 👉️ "Sun Jan 16 2022 10:22:07"

The toLocaleString method returns a locale-specific string that is adjusted to the provided time zone.

Copied!
const date = new Date(); console.log( date.toLocaleString('en-US', timeZone: 'America/New_York', >), ); // 👉️ "1/12/2023, 12:32:01 PM" console.log( date.toLocaleString('ca-CA', timeZone: 'Canada/Pacific', >), ); // 👉️ "12/1/2023 9:32:01"

The changeTimeZone function can be passed a date string or a Date object and returns a Date object with the date and time corresponding to the provided time zone.

The two parameters we passed to the toLocaleString method are:

  1. locales — a string with a BCP 47 language tag or an array of such strings. You can use any of the available locales, e.g. es-MX for Mexico or en-CA for Canada. If you need more information about this parameter, check out the MDN docs.
  2. options object where we specified the timeZone property. Read more about the options object in the MDN docs.

You can find a table of the country codes and time zone database names by visiting this wikipedia page.

It stores a timestamp that represents the number of milliseconds that have passed since midnight on January 1st, 1970.

The date and time of the Date object correspond to the time zone, however, the Date object has no way of storing the specific time zone.

For this reason, it’s best to use the toLocaleString method to get a string that represents the time zone and use the options object parameter to format the string according to your needs.

You can use the different properties on the options object of the toLocaleString method to format the date and time for the specific time zone in different ways.

Copied!
const date = new Date(); console.log( date.toLocaleString('en-US', timeZone: 'America/New_York', dateStyle: 'full', timeStyle: 'full', >), ); // 👉️ "Sunday, January 16, 2022 at 4:42:40 AM Eastern Standard Time"

We set the dateStyle and timeStyle properties in the options object to full to get a more verbose representation of the date and time.

Other possible values for the two properties are: long , medium and short .

Copied!
const date = new Date(); console.log( date.toLocaleString('en-US', timeZone: 'America/New_York', dateStyle: 'short', timeStyle: 'short', >), ); // 👉️ "1/16/22, 4:43 AM"

You can view all of the properties and values the options object implements by visiting the MDN docs.

Here is an example that shows the month, day, hours, minutes and seconds as 2-digits, even if their values are less than 10 .

Copied!
const date = new Date(); console.log( date.toLocaleString('en-US', timeZone: 'America/New_York', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', timeZoneName: 'short', >), ); // 👉️ "01/16/2022, 04:43:39 AM EST"

By setting the values of the date and time components to 2 digits, we format them consistently, even if they have a value of less than 10 .

If that’s the case, the values get padded with a leading zero.

We also set the timeZoneName property to a value of short , to show an abbreviation of the time zone name at the end of the result.

You can view all the other properties the options object supports by visiting the MDN docs.

You can get a time zone-specific date and time representation formatted in many different ways by just using the toLocaleString method and this should be your preferred approach as it leverages built-in functionality.

# The toLocaleString() method uses the Intl.DateTimeFormat API

The toLocaleString() method calls the Intl.DateTimeFormat API under the hood.

The Intl.DateTimeFormat() constructor creates an Intl.DateTimeFormat object that enables language-sensitive date and time formatting.

Copied!
const date = new Date(); // US English uses month-day-year order console.log(new Intl.DateTimeFormat('en-US').format(date)); // "1/12/2023" // British English uses day-month-year order console.log(new Intl.DateTimeFormat('en-GB').format(date)); // "12/01/2023" // German uses day-month-year order console.log(new Intl.DateTimeFormat('de-DE').format(date)); // "12.1.2023"

The Intl.DateTimeFormat() constructor returns an object on which we can call the format() method.

The format() method formats a date according to the locale and the supplied formatting options.

The format() method returns a string, just like the toLocaleString() method.

The Intl.DateTimeFormat() constructor can also be passed an options object and supports the same properties and values as the toLocaleString method.

Copied!
const date = new Date(); const options = year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false, timeZone: 'America/Los_Angeles', >; // US English uses month-day-year order console.log(new Intl.DateTimeFormat('en-US', options).format(date)); // "1/12/2023, 09:13:57"

All of the properties and values the object method supports are documented in this section of the MDN docs.

You could use either approach to get a language-sensitive representation of a date, but the toLocaleString method is more convenient and provides a higher level of abstraction.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Python decorator in class method
Оцените статью