How to initialize a JavaScript Date to a particular time zone

I have date time in a particular timezone as a string and I want to convert this to the local time. But, I don't know how to set the timezone in the Date object.

For example, I have Feb 28 2013 7:00 PM ET, then I can

var mydate = new Date();
mydate.setFullYear(2013);
mydate.setMonth(02);
mydate.setDate(28);
mydate.setHours(7);
mydate.setMinutes(00);  

As far as I know, I can either set the UTC time or local time. But, how do I set time in another timezone?

I tried to use the add/subtract the offset from UTC but I don't know how to counter daylight savings. Am not sure if I am heading the right direction.

How can I go about converting time from a different timezone to local time in javascript?

Answers:

Answer

Background

JavaScript's Date object tracks time in UTC internally, but typically accepts input and output in the local time of the computer it's running on. It doesn't have any facilities for working with time in other time zones. It can parse and output dates that are UTC or Local, but it can't directly work with other time zones.

To be absolutely precise, the internal representation of a Date object is a single number, 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.

Libraries

Fortunately, there are 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 Olson/IANA timezone database and provide functions for using it in JavaScript. Some have overhead if you are running in a web browser, as the database can get a bit large if you want the whole thing. Fortunately, many of these libraries allow you to selectively choose which zones you want to support, making the data size much more palatable. Also some use modern features to get time zone data from the Intl API instead of having to ship it themselves.

There are several libraries for this that I am aware of:

Luxon is probably the safest bet for all modern usage, and is the lightest weight as it uses the Intl API for its timezone data.

Moment-timezone is an extension to moment.js, and brings its own time zone data.

js-joda is a JavaScript implementation of the Joda-Time API (from Java), and includes time zone support through a separate module.

date-fns-tz is an extension for date-fns 2.x. date-fns-timezone is an extension for date-fns 1.x.

BigEasy/TimeZone also appears to be on the right track.

WallTime-js has reached end-of-life, and the owners are migrating to moment-timezone.

TimeZoneJS has been around the longest, but is known to have some long-standing bugs, especially near daylight saving time transitions. Hopefully these will be fixed at some point in the future.

tz.js has also been around for some time, but isn't very well documented, IMHO.

You should evaluate these libraries to see which will meet your needs. If unsure, go with moment/moment-timezone.

Native Support in Modern Environments

If you can limit your usage to modern environments, 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). This is part of the ECMAScript Internationalization API (ECMA-402). See this post for more details. This compatibility table tracks which versions are supported. This is the Intl API mentioned above that certain libraries are using internally now.

(To be clear, this doesn't initialize a Date object, but can be used to apply a time zone when producing a locale-specific string representation.)

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.

Answer

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:

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);

}

// E.g.
var there = new Date();
var here = changeTimezone(there, "America/Toronto");

console.log(`Here: ${here.toString()}\nToronto: ${there.toString()}`);

Answer

You can specify a time zone offset on new Date(), for example:

new Date('Feb 28 2013 19:00:00 EST')

or

new Date('Feb 28 2013 19:00:00 GMT-0500')

Since Date store UTC time ( i.e. getTime returns in UTC ), javascript will them convert the time into UTC, and when you call things like toString javascript will convert the UTC time into browser's local timezone and return the string in local timezone, i.e. If I'm using UTC+8:

> new Date('Feb 28 2013 19:00:00 GMT-0500').toString()
< "Fri Mar 01 2013 08:00:00 GMT+0800 (CST)"

Also you can use normal getHours/Minute/Second method:

> new Date('Feb 28 2013 19:00:00 GMT-0500').getHours()
< 8

( This 8 means after the time is converted into my local time - UTC+8, the hours number is 8. )

Answer

This should solve your problem, please feel free to offer fixes. This method will account also for daylight saving time for the given date.

dateWithTimeZone = (timeZone, year, month, day, hour, minute, second) => {
  let date = new Date(Date.UTC(year, month, day, hour, minute, second));

  let utcDate = new Date(date.toLocaleString('en-US', { timeZone: "UTC" }));
  let tzDate = new Date(date.toLocaleString('en-US', { timeZone: timeZone }));
  let offset = utcDate.getTime() - tzDate.getTime();

  date.setTime( date.getTime() + offset );

  return date;
};

How to use with timezone and local time:

dateWithTimeZone("America/Los_Angeles",2019,8,8,0,0,0)
Answer

I found the most supported way to do this, without worrying about a third party library, was by using getTimezoneOffset to calculate the appropriate timestamp, or update the time then use the normal methods to get the necessary date and time.

var mydate = new Date();
mydate.setFullYear(2013);
mydate.setMonth(02);
mydate.setDate(28);
mydate.setHours(7);
mydate.setMinutes(00);

// ET timezone offset in hours.
var timezone = -5;
// Timezone offset in minutes + the desired offset in minutes, converted to ms.
// This offset should be the same for ALL date calculations, so you should only need to calculate it once.
var offset = (mydate.getTimezoneOffset() + (timezone * 60)) * 60 * 1000;

// Use the timestamp and offset as necessary to calculate min/sec etc, i.e. for countdowns.
var timestamp = mydate.getTime() + offset,
    seconds = Math.floor(timestamp / 1000) % 60,
    minutes = Math.floor(timestamp / 1000 / 60) % 60,
    hours   = Math.floor(timestamp / 1000 / 60 / 60);

// Or update the timestamp to reflect the timezone offset.
mydate.setTime(mydate.getTime() + offset);
// Then Output dates and times using the normal methods.
var date = mydate.getDate(),
    hour = mydate.getHours();

EDIT

I was previously using UTC methods when performing the date transformations, which was incorrect. With adding the offset to the time, using the local get functions will return the desired results.

Answer

I ran into a similar problem with unit tests (specifically in jest when the unit tests run locally to create the snapshots and then the CI server runs in (potentially) a different timezone causing the snapshot comparison to fail). I mocked our Date and some of the supporting methods like so:

describe('...', () => {
  let originalDate;

  beforeEach(() => {
    originalDate = Date;
    Date = jest.fn(
      (d) => {
        let newD;
        if (d) {
          newD = (new originalDate(d));
        } else {
          newD = (new originalDate('2017-05-29T10:00:00z'));
        }
        newD.toLocaleString = () => {
          return (new originalDate(newD.valueOf())).toLocaleString("en-US", {timeZone: "America/New_York"});
        };
        newD.toLocaleDateString = () => {
          return (new originalDate(newD.valueOf())).toLocaleDateString("en-US", {timeZone: "America/New_York"});
        };
        newD.toLocaleTimeString = () => {
          return (new originalDate(newD.valueOf())).toLocaleTimeString("en-US", {timeZone: "America/New_York"});
        };
        return newD;
      }
    );
    Date.now = () => { return (Date()); };
  });

  afterEach(() => {
    Date = originalDate;
  });

});
Answer

Try using ctoc from npm. https://www.npmjs.com/package/ctoc_timezone

It has got simple functionality to change timezones (most timezones around 400) and all custom formats u want it to display.

Answer

Building on the answers above, I am using this native one liner to convert the long timezone string to the three letter string:

var longTz = 'America/Los_Angeles';
var shortTz = new Date().
    toLocaleString("en", {timeZoneName: "short", timeZone: longTz}).
    split(' ').
    pop();

This will give PDT or PST depending on the date provided. In my particular use case, developing on Salesforce (Aura/Lightning), we are able to get the user timezone in the long format from the backend.

Answer

I know its 3 years too late, but maybe it can help someone else because I haven't found anything like that except for the moment-timezone library, which is not exactly the same as what he's asking for here.

I've done something similar for german timezone, this is a little complex because of daylight saving time and leap years where you have 366 days.

it might need a little work with the "isDaylightSavingTimeInGermany" function while different timezones change on different times the daylight saving time.

anyway, check out this page: https://github.com/zerkotin/german-timezone-converter/wiki

the main methods are: convertLocalDateToGermanTimezone convertGermanDateToLocalTimezone

I've put an effort into documenting it, so it won't be so confusing.

Answer

Try: date-from-timezone, it resolves expected date with help of natively available Intl.DateTimeFormat.

I used that method in one of my projects for few years already, but it's now I decided to publish it as small OS project :)

Answer

For Ionic users, I had hell with this because .toISOString() has to be used with the html template.

This will grab the current date, but of course can be added to previous answers for a selected date.

I got it fixed using this:

date = new Date();
public currentDate: any = new Date(this.date.getTime() - this.date.getTimezoneOffset()*60000).toISOString();

The *60000 is indicating the UTC -6 which is CST so whatever TimeZone is needed, the number and difference can be changed.

Answer

Was facing the same issue, used this one

Console.log(Date.parse("Jun 13, 2018 10:50:39 GMT+1"));

It will return milliseconds to which u can check have +100 timzone intialize British time Hope it helps!!

Answer

Maybe this will help you

/**
 * Shift any Date timezone.
 * @param {Date} date - Date to update.
 * @param {string} timezone - Timezone as `-03:00`.
 */
function timezoneShifter(date, timezone) {
  let isBehindGTM = false;
  if (timezone.startsWith("-")) {
    timezone = timezone.substr(1);
    isBehindGTM = true;
  }

  const [hDiff, mDiff] = timezone.split(":").map((t) => parseInt(t));
  const diff = hDiff * 60 + mDiff * (isBehindGTM ? 1 : -1);
  const currentDiff = new Date().getTimezoneOffset();

  return new Date(date.valueOf() + (currentDiff - diff) * 60 * 1000);
}



const _now = new Date()
console.log(
  [
    "Here: " + _now.toLocaleString(),
    "Greenwich: " + timezoneShifter(_now, "00:00").toLocaleString(),
    "New York: " + timezoneShifter(_now, "-04:00").toLocaleString(),
    "Tokyo: " + timezoneShifter(_now, "+09:00").toLocaleString(),
    "Buenos Aires: " + timezoneShifter(_now, "-03:00").toLocaleString(),
  ].join('\n')
);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.