Convert Date to Another Timezone in JavaScript

Convert date to another timezone in JavaScript

Here is the one-liner:

function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}

// usage: Asia/Jakarta is GMT+7
convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time)

// Resulting value is regular Date() object
const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta")
convertedDate.getHours(); // 17

// Bonus: You can also put Date object to first arg
const date = new Date()
convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.

Convert Date to another timezone in JavaScript and Print with Correct Timezone

A few things:

  • The approach in the answer you linked to for the convertTZ is flawed. One should not parse the output of toLocalString with the Date constructor. Please read the comments following that answer.

  • The Date object can not be converted to another time zone, because it is not actually in any time zone. The only thing encapsulated by the Date object is its Unix timestamp, which can be seen with .valueOf(), .getTime(), or any mechanism that coerces it to a Number. Such values are always UTC-based.

  • When you see local time or a time zone coming from the Date object, the system's local time zone is applied to the internal UTC-based Unix Timestamp to create the output. The local time zone cannot be changed programmatically from JavaScript (or TypeScript), nor can it be altered on a per-object basis.

  • Instead of trying to convert a Date object in one time zone to a Date object in another time zone, recognize that all Date objects are inherently UTC. Thus, you can create a string that is in a different time zone, (for example, using toLocaleString with the timeZone option) but you cannot create a new Date object from that string. If you want an object that can actually be set to a different time zone, consider Luxon. If you need a solution without a library, you will one day be able to use a ZonedDateTime from the TC39 Temporal Proposal, which will eventually be part of ECMAScript.

  • Beware of calling console.log on a Date object. Neither the ECMAScript spec nor the WhatWG Console spec defines the behavior of such a call. It is undefined behavior. In some environments, the string output logged is the same as calling .toString() on the Date object - which will give the local time equivalent of the Date object's timestamp, along with a display name for the local time zone. Other environments will show the same output of calling .toISOString(), which will give an ISO-8601 representation of the timestamp in UTC. Instead of logging Date objects, call one of those two functions yourself and log the output.

How to convert javascript date to a particular timezone

I understand that you wanted to get a same time irrespective of time zone when ever you pass the milliseconds.

instead of the following two lines

    var d = new Date(dt)
var os = d.getTimezoneOffset();

you include the below lines

    var os = new Date()
os = os.getTimezoneOffset();
var d = new Date((dt + (os * 60 * 1000)));

This adjusts your milliseconds to UTC time based on your local timezone and creates the date object from the adjusted UTC time, so that you will always get same time, irrespective of your local time zone.

Create a Date with a set timezone without using a string representation

using .setUTCHours() it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.

You cannot set it using UTC in the constructor though, unless you specify a date-string.

Using new Date(Date.UTC(year, month, day, hour, minute, second)) you can create a Date-object from a specific UTC time.

How to convert date from one timezone to another timezone

To get time zone support for date-fns, you will need the date-fns-tz add-on module.

Then you can do the following:

import { zonedTimeToUtc } from 'date-fns-tz';

const dt = zonedTimeToUtc('2020-10-13', 'America/Chicago');

The result will be a Date object that represents midnight in the given time zone.

Keep in mind that Date objects themselves are always UTC-based. Thus, you can't get a Date object that is "in" a different time zone.

Also, you should pass a string into the zonedTimeToUtc function as shown. You should not pass it to the Date object. As mentioned in comments, the ECMAScript spec says that a date-only string value should be parsed as UTC. However, there are still some implementations that don't follow the spec correctly. Thus, you should avoid parsing strings using the Date object constructor.

Converting time to another timezone JS

Consider using Luxon - the successor to Moment. (See Moment's project status.)

// Parse your input string using the user's local time zone
// (this assumes the current local date)
const local = luxon.DateTime.fromFormat('1:30 pm', 'h:mm a');

// Convert to the desired time zone
const converted = local.setZone('America/Los_Angeles');

// Format the output as desired
const formatted = converted.toFormat('dd/MM/yyyy h:mm a').toLowerCase();

console.log(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.4.0/luxon.min.js"></script>


Related Topics



Leave a reply



Submit