How to initialize a JavaScript Date to a particula

2018-12-30 23:59发布

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?

9条回答
浅入江南
2楼-- · 2018-12-31 00:26

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

查看更多
裙下三千臣
3楼-- · 2018-12-31 00:31

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

查看更多
孤独总比滥情好
4楼-- · 2018-12-31 00:34

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,iana) {

     // suppose the date is 12:00 UTC
     var invdate = new Date(date.toLocaleString('en-US', { 
        timeZone: iana 
     }));

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

   }
查看更多
无色无味的生活
5楼-- · 2018-12-31 00:36

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() + timezone_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() + timezone_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.

查看更多
柔情千种
6楼-- · 2018-12-31 00:39

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 Browsers

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

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.

查看更多
谁念西风独自凉
7楼-- · 2018-12-31 00:40

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

ive 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

ive put an effort into documenting it, so it wont be so confusing.

查看更多
登录 后发表回答