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 oftoLocalString
with theDate
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 theDate
object is its Unix timestamp, which can be seen with.valueOf()
,.getTime()
, or any mechanism that coerces it to aNumber
. 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 aDate
object in another time zone, recognize that allDate
objects are inherently UTC. Thus, you can create a string that is in a different time zone, (for example, usingtoLocaleString
with thetimeZone
option) but you cannot create a newDate
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 aZonedDateTime
from the TC39 Temporal Proposal, which will eventually be part of ECMAScript.Beware of calling
console.log
on aDate
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 theDate
object - which will give the local time equivalent of theDate
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 loggingDate
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
How to Remove All Duplicates from an Array of Objects
Uncaught Referenceerror: $ Is Not Defined
Settimeout in For-Loop Does Not Print Consecutive Values
Why Is Setstate in Reactjs Async Instead of Sync
What's the Difference Between '$(This)' and 'This'
How to Insert an Element After Another Element in JavaScript Without Using a Library
How to Get a Key in a JavaScript Object by Its Value
Methods in Es6 Objects: Using Arrow Functions
How to Round to At Most 2 Decimal Places, If Necessary
Sorting in JavaScript: Shouldn't Returning a Boolean Be Enough For a Comparison Function
Looping Through Array and Removing Items, Without Breaking For Loop
What Does "Use Strict" Do in JavaScript, and What Is the Reasoning Behind It
How to Find the Sum of an Array of Numbers