Background
JavaScript's Date object tracks time in UTC internally, but typically accepts input and produces output in the local time of the computer it's running on. It has very few facilities for working with time in other time zones.
The internal representation of a Date object is a single number - namely timestamp - representing the number of milliseconds that have elapsed since 1970-01-01 00:00:00 UTC, without regard to leap seconds.
There is no time zone or string format stored in the Date object itself.
When various functions of the Date object are used, the computer's local time zone is applied to the internal representation. If the function produces a string, then the computer's locale information may be taken into consideration to determine how to produce that string. The details vary per function, and some are implementation-specific.
The only operations the Date object can do with non-local time zones are:
It can parse a string containing a numeric UTC offset from any time zone. It uses this to adjust the value being parsed, and stores the UTC equivalent. The original local time and offset are not retained in the resulting
Dateobject. For example:var d = new Date("2020-04-13T00:00:00.000+08:00"); d.toISOString() //=> "2020-04-12T16:00:00.000Z" d.valueOf() //=> 1586707200000 (this is what is actually stored in the object)In environments that have implemented the ECMASCript Internationalization API (aka "Intl"), a
Dateobject can produce a locale-specific string adjusted to a given time zone identifier. This is accomplished via thetimeZoneoption totoLocaleStringand its variations. Most implementations will support IANA time zone identifiers, such as'America/New_York'. For example:var d = new Date("2020-04-13T00:00:00.000+08:00"); d.toLocaleString('en-US', { timeZone: 'America/New_York' }) //=> "4/12/2020, 12:00:00 PM" // (midnight in China on April 13th is noon in New York on April 12th)Most modern environments support the full set of IANA time zone identifiers (see the compatibility table here). However, keep in mind that the only identifier required to be supported by Intl is
'UTC', thus you should check carefully if you need to support older browsers or atypical environments (for example, lightweight IoT devices).
Libraries
There are several libraries that can be used to work with time zones. Though they still cannot make the Date object behave any differently, they typically implement the standard IANA timezone database and provide functions for using it in JavaScript. Modern libraries use the time zone data supplied by the Intl API, but older libraries typically have overhead, especially if you are running in a web browser, as the database can get a bit large. Some of these libraries also allow you to selectively reduce the data set, either by which time zones are supported and/or by the range of dates you can work with.
Here are the libraries to consider:
Intl-based Libraries
New development should choose from one of these implementations, which rely on the Intl API for their time zone data:
- Luxon (successor of Moment.js)
- date-fns-tz (extension for date-fns)
- Day.js (when using its Timezone plugin)
Non-Intl Libraries
These libraries are maintained, but carry the burden of packaging their own time zone data, which can be quite large.
- js-joda/timezone (extension for js-joda)
- moment-timezone* (extension for Moment.js)
- date-fns-timezone (extension for older 1.x of date-fns)
- BigEasy/TimeZone
- tz.js
* While Moment and Moment-Timezone were previously recommended, the Moment team now prefers users chose Luxon for new development.
Discontinued Libraries
These libraries have been officially discontinued and should no longer be used.
- WallTime-js
- TimeZoneJS
Future Proposals
The TC39 Temporal Proposal aims to provide a new set of standard objects for working with dates and times in the JavaScript language itself. This will include support for a time zone aware object.
Common Errors
There are several approaches that are often tried, which are in error and should usually be avoided.
Re-Parsing
new Date(new Date().toLocaleString('en', {timeZone: 'America/New_York'}))
The above approach correctly uses the Intl API to create a string in a specific time zone, but then it incorrectly passes that string back into the Date constructor. In this case, parsing will be implementation-specific, and may fail entirely. If successful, it is likely that the resulting Date object now represents the wrong instant in time, as the computer's local time zone would be applied during parsing.
Epoch Shifting
var d = new Date();
d.setTime(d.getTime() + someOffset * 60000);
The above approach attempts to manipulate the Date object's time zone by shifting the Unix timestamp by some other time zone offset. However, since the Date object only tracks time in UTC, it actually just makes the Date object represent a different point in time.
The same approach is sometimes used directly on the constructor, and is also invalid.
Epoch Shifting is sometimes used internally in date libraries as a shortcut to avoid writing calendar arithmetic. When doing so, any access to non-UTC properties must be avoided. For example, once shifted, a call to getUTCHours would be acceptable, but a call to getHours would be invalid because it uses the local time zone.
It is called "epoch shifting", because when used correctly, the Unix Epoch (1970-01-01T00:00:00.000Z) is now no longer correlated to a timestamp of 0 but has shifted to a different timestamp by the amount of the offset.
If you're not authoring a date library, you should not be epoch shifting.
For more details about epoch shifting, watch this video clip from Greg Miller at CppCon 2015. The video is about time_t in C++, but the explanation and problems are identical. (For JavaScript folks, every time you hear Greg mention time_t, just think "Date object".)
Trying to make a "UTC Date"
var d = new Date();
var utcDate = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()));
In this example, both d and utcDate are identical. The work to construct utcDate was redundant, because d is already in terms of UTC. Examining the output of toISOString, getTime, or valueOf functions will show identical values for both variables.
A similar approach seen is:
var d = new Date();
var utcDate = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds());
This is approach passes UTC values into the Date constructor where local time values are expected. The resulting Date object now represents a completely different point in time. It is essentially the same result as epoch shifting described earlier, and thus should be avoided.
The correct way to get a UTC-based Date object is simply new Date(). If you need a string representation that is in UTC, then use new Date().toISOString().
Background
JavaScript's Date object tracks time in UTC internally, but typically accepts input and produces output in the local time of the computer it's running on. It has very few facilities for working with time in other time zones.
The internal representation of a Date object is a single number - namely timestamp - representing the number of milliseconds that have elapsed since 1970-01-01 00:00:00 UTC, without regard to leap seconds.
There is no time zone or string format stored in the Date object itself.
When various functions of the Date object are used, the computer's local time zone is applied to the internal representation. If the function produces a string, then the computer's locale information may be taken into consideration to determine how to produce that string. The details vary per function, and some are implementation-specific.
The only operations the Date object can do with non-local time zones are:
It can parse a string containing a numeric UTC offset from any time zone. It uses this to adjust the value being parsed, and stores the UTC equivalent. The original local time and offset are not retained in the resulting
Dateobject. For example:var d = new Date("2020-04-13T00:00:00.000+08:00"); d.toISOString() //=> "2020-04-12T16:00:00.000Z" d.valueOf() //=> 1586707200000 (this is what is actually stored in the object)In environments that have implemented the ECMASCript Internationalization API (aka "Intl"), a
Dateobject can produce a locale-specific string adjusted to a given time zone identifier. This is accomplished via thetimeZoneoption totoLocaleStringand its variations. Most implementations will support IANA time zone identifiers, such as'America/New_York'. For example:var d = new Date("2020-04-13T00:00:00.000+08:00"); d.toLocaleString('en-US', { timeZone: 'America/New_York' }) //=> "4/12/2020, 12:00:00 PM" // (midnight in China on April 13th is noon in New York on April 12th)Most modern environments support the full set of IANA time zone identifiers (see the compatibility table here). However, keep in mind that the only identifier required to be supported by Intl is
'UTC', thus you should check carefully if you need to support older browsers or atypical environments (for example, lightweight IoT devices).
Libraries
There are several libraries that can be used to work with time zones. Though they still cannot make the Date object behave any differently, they typically implement the standard IANA timezone database and provide functions for using it in JavaScript. Modern libraries use the time zone data supplied by the Intl API, but older libraries typically have overhead, especially if you are running in a web browser, as the database can get a bit large. Some of these libraries also allow you to selectively reduce the data set, either by which time zones are supported and/or by the range of dates you can work with.
Here are the libraries to consider:
Intl-based Libraries
New development should choose from one of these implementations, which rely on the Intl API for their time zone data:
- Luxon (successor of Moment.js)
- date-fns-tz (extension for date-fns)
- Day.js (when using its Timezone plugin)
Non-Intl Libraries
These libraries are maintained, but carry the burden of packaging their own time zone data, which can be quite large.
- js-joda/timezone (extension for js-joda)
- moment-timezone* (extension for Moment.js)
- date-fns-timezone (extension for older 1.x of date-fns)
- BigEasy/TimeZone
- tz.js
* While Moment and Moment-Timezone were previously recommended, the Moment team now prefers users chose Luxon for new development.
Discontinued Libraries
These libraries have been officially discontinued and should no longer be used.
- WallTime-js
- TimeZoneJS
Future Proposals
The TC39 Temporal Proposal aims to provide a new set of standard objects for working with dates and times in the JavaScript language itself. This will include support for a time zone aware object.
Common Errors
There are several approaches that are often tried, which are in error and should usually be avoided.
Re-Parsing
new Date(new Date().toLocaleString('en', {timeZone: 'America/New_York'}))
The above approach correctly uses the Intl API to create a string in a specific time zone, but then it incorrectly passes that string back into the Date constructor. In this case, parsing will be implementation-specific, and may fail entirely. If successful, it is likely that the resulting Date object now represents the wrong instant in time, as the computer's local time zone would be applied during parsing.
Epoch Shifting
var d = new Date();
d.setTime(d.getTime() + someOffset * 60000);
The above approach attempts to manipulate the Date object's time zone by shifting the Unix timestamp by some other time zone offset. However, since the Date object only tracks time in UTC, it actually just makes the Date object represent a different point in time.
The same approach is sometimes used directly on the constructor, and is also invalid.
Epoch Shifting is sometimes used internally in date libraries as a shortcut to avoid writing calendar arithmetic. When doing so, any access to non-UTC properties must be avoided. For example, once shifted, a call to getUTCHours would be acceptable, but a call to getHours would be invalid because it uses the local time zone.
It is called "epoch shifting", because when used correctly, the Unix Epoch (1970-01-01T00:00:00.000Z) is now no longer correlated to a timestamp of 0 but has shifted to a different timestamp by the amount of the offset.
If you're not authoring a date library, you should not be epoch shifting.
For more details about epoch shifting, watch this video clip from Greg Miller at CppCon 2015. The video is about time_t in C++, but the explanation and problems are identical. (For JavaScript folks, every time you hear Greg mention time_t, just think "Date object".)
Trying to make a "UTC Date"
var d = new Date();
var utcDate = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()));
In this example, both d and utcDate are identical. The work to construct utcDate was redundant, because d is already in terms of UTC. Examining the output of toISOString, getTime, or valueOf functions will show identical values for both variables.
A similar approach seen is:
var d = new Date();
var utcDate = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds());
This is approach passes UTC values into the Date constructor where local time values are expected. The resulting Date object now represents a completely different point in time. It is essentially the same result as epoch shifting described earlier, and thus should be avoided.
The correct way to get a UTC-based Date object is simply new Date(). If you need a string representation that is in UTC, then use new Date().toISOString().
As Matt Johnson said
If you can limit your usage to modern web browsers, you can now do the following without any special libraries:
new Date().toLocaleString("en-US", {timeZone: "America/New_York"})
This isn't a comprehensive solution, but it works for many scenarios that require only output conversion (from UTC or local time to a specific time zone, but not the other direction).
So although the browser can not read IANA timezones when creating a date, or has any methods to change the timezones on an existing Date object, there seems to be a hack around it.
Consider the following function
function changeTimezone(date, ianatz) {
// suppose the date is 12:00 UTC
var invdate = new Date(date.toLocaleString('en-US', {
timeZone: ianatz
}));
// then invdate will be 07:00 in Toronto
// and the diff is 5 hours
var diff = date.getTime() - invdate.getTime();
// so 12:00 in Toronto is 17:00 UTC
return new Date(date.getTime() - diff); // needs to substract
}
However, closely looking at the return value, this can be simplified to:
function changeTimezone(date, ianatz) {
return new Date(date.toLocaleString('en-US', {
timeZone: ianatz
}));
}
// E.g.
var here = new Date();
var there = changeTimezone(here, "America/Toronto");
console.log(`Here: ${here.toString()}\nToronto: ${there.toString()}`);
JavaScript will use the client's local time but it also has UTC / GMT methods. The following is from Mozilla:
The JavaScript Date object supports a number of UTC (universal) methods, as well as local time methods. UTC, also known as Greenwich Mean Time (GMT), refers to the time as set by the World Time Standard. The local time is the time known to the computer where JavaScript is executed.
While methods are available to access date and time in both UTC and the localtime zone, the date and time are stored in the local time zone:
Note: It's important to keep in mind that the date and time is stored in the local time zone, and that the basic methods to fetch the date and time or its components all work in the local time zone as well.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
What time zone does the Javascript new Date() use?
Date objects store the number of milliseconds since The Epoch (Jan 1st 1970 at midnight GMT). They have methods like getDay and getMonth and such that provide values in the local timezone, and also functions like getUTCDay and getUTCMonth that provide values in UTC (loosely, GMT).
If you're parsing a string, you need to be sure that the string is in a format that Date knows how to parse. The only defined format in the specification is a simplified derivative of ISO-8601: YYYY-MM-DDTHH:mm:ss.sssZ. But that was only added in ES5 (and then updated in ES2015 and ES2016). The time zone of the string is determined by whether it has a UTC offset indicator (Z, -08:00, +05:30, etc.) and whether it's date-only or date/time. Here are some examples:
function test(str) {
const dt = new Date(str);
const p = document.createElement("pre");
p.textContent =
`String: "${str}"\n` +
`UTC: ${dt.toISOString()}\n` +
`Local: ${dt.toLocaleString()}`
;
document.body.appendChild(p);
}
// No UTC offset provided, date-only form => parsed as UTC:
test("2015-08-09");
// No UTC offset provided, date/time form => parsed as local time:
test("2015-08-09T09:32:54");
// Has UTC offset "Z" (for "no offset") => parsed as UTC:
test("2015-08-09T09:32:54.427Z");
// Has UTC offset -08:00 => parsed as UTC minus eight hours:
test("2015-08-09T09:32:54.427-08:00");
I don't recommend relying on it, but even though it's not specified, all major JavaScript engines will successfully parse the American-specific formats MM/DD/YYYY, MM/DD/YYYY hh:mm, MM/DD/YYYY hh:mm:ss, or MM/DD/YYYY hh:mm:ss.SSS (although the milliseconds portion is ignored by some). Note the order in the date portion: month, day, year. Having a UTC offset indicator is not broadly supported and will cause an error on most engines, so don't include one. Without one, all of those are parsed as local time (even the date-only one). Note that the date field separator must be / (08/09/2015), not - (08-09-2015).
function test(str) {
const dt = new Date(str);
const p = document.createElement("pre");
p.textContent =
`String: "${str}"\n` +
`UTC: ${dt.toISOString()}\n` +
`Local: ${dt.toLocaleString()}`
;
document.body.appendChild(p);
}
test("08/09/2015");
test("08/09/2015 09:32");
test("08/09/2015 09:32:54");
test("08/09/2015 09:32:54.427");
But again: I don't recommend relying on that.
Using an offset to calculate Timezone is a wrong approach, and you will always encounter problems. Time zones and daylight saving rules may change on several occasions during a year, and It's difficult to keep up with changes.
To get the system's IANA timezone in JavaScript, you should use
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)
As of April 2023, this works in 95.42% of the browsers used globally.
Old compatibility information
ecma-402/1.0 says that timeZone may be undefined if not provided to constructor. However, future draft (3.0) fixed that issue by changing to system default timezone.
In this version of the ECMAScript Internationalization API, the
timeZoneproperty will remain undefined if notimeZoneproperty was provided in the options object provided to theIntl.DateTimeFormatconstructor. However, applications should not rely on this, as future versions may return a String value identifying the host environment’s current time zone instead.
in ecma-402/3.0 which is still in a draft it changed to
In this version of the ECMAScript 2015 Internationalization API, the
timeZoneproperty will be the name of the default time zone if notimeZoneproperty was provided in the options object provided to theIntl.DateTimeFormatconstructor. The previous version left thetimeZoneproperty undefined in this case.
Using getTimezoneOffset()
You can get the time zone offset in minutes like this:
var offset = new Date().getTimezoneOffset();
console.log(offset);
// if offset equals -60 then the time zone offset is UTC+01
The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight savings time prevents this value from being a constant even for a given locale
- Mozilla Date Object reference
Note that not all timezones are offset by whole hours: for example, Newfoundland is UTC minus 3h 30m (leaving Daylight Saving Time out of the equation).
Please also note that this only gives you the time zone offset (eg: UTC+01), it does not give you the time zone (eg: Europe/London).