• Post category:JavaScript
  • Reading time:5 mins read

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.

Steps to convert local time to another timezone

  1. Get current local time in milliseconds
  2. Find the local timezone offset
  3. Obtain the current UTC time
  4. Get destination city’s UTC offset in hours
  5. Get date of another timezone in readable datetime

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..!!

Leave a Reply