如何在不使用字符串表示的情况下创建具有设置时区的JavaScript日期对象

时间:2022-08-10 01:19:30

I have a web page with three dropdowns for day, month and year. If I use the JavaScript Date constructor that takes numbers then I get a Date object for my current timezone:

我有一个网页,每天、每月、每年都有三个下拉。如果我使用带有数字的JavaScript日期构造函数,那么我将获得当前时区的日期对象:

new Date(xiYear, xiMonth, xiDate)

Give the correct date but it thinks that date is GMT+01:00 due to daylight savings time.

给出正确的日期,但是它认为是GMT+01:00,因为夏令时。

The problem here is that I then give this Date to an Ajax method and when the date is deserialised on the server it has been converted to GMT and so lost an hour which moves the day back by one. Now I could just pass the day, month, and year individually into the Ajax method but it seems that there ought to be a better way.

这里的问题是,我将这个日期提供给一个Ajax方法,当这个日期在服务器上被反序列化时,它已经被转换为GMT,因此丢失了一个小时,这将使日期返回一个小时。现在我可以将一天、一月、一年的时间单独地放到Ajax方法中,但似乎应该有更好的方法。

The accepted answer pointed me in the right direction, however just using setUTCHours by itself changed:

这个公认的答案让我找到了正确的方向,但是仅仅使用setUTCHours本身就改变了:

Apr 5th 00:00 GMT+01:00 

to

Apr 4th 23:00 GMT+01:00

I then also had to set the UTC date, month and year to end up with

然后我还要设定UTC日期、月份和年份

Apr 5th 01:00 GMT+01:00

which is what I wanted

这就是我想要的?

17 个解决方案

#1


407  

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

使用. setutchours()可以在utctime中设置日期,这将允许您在整个系统中使用UTC-times。

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

但是,除非指定日期字符串,否则不能在构造函数中使用UTC设置它。

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

使用新的日期(日期。UTC(年、月、日、小时、分钟、秒)您可以从特定的UTC时间创建一个日期对象。

#2


166  

var d = new Date(xiYear, xiMonth, xiDate);
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );

When this date object is deserialized, you might get the information you expect.

当这个日期对象被反序列化时,您可能会得到您期望的信息。

#3


122  

I believe you need the createDateAsUTC function (please compare with convertDateToUTC)

我相信您需要createDateAsUTC函数(请与convertDateToUTC进行比较)

function createDateAsUTC(date) {
    return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
}

function convertDateToUTC(date) { 
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()); 
}

#4


23  

I don't believe this is possible - there is no ability to set the timezone on a Date object after it is created.

我认为这是不可能的——在创建日期对象之后,没有能力对其设置时区。

And in a way this makes sense - conceptually (if perhaps not in implementation); per http://en.wikipedia.org/wiki/Unix_timestamp (emphasis mine):

在某种程度上,这是有意义的——从概念上来说(如果不是在实施中);我每http://en.wikipedia.org/wiki/Unix_timestamp(重点):

Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970.

Unix时间(POSIX time)是一个系统,用于描述时间上的瞬间,定义为自1970年1月1日星期四午夜协调世界时(UTC)以来的秒数。

Once you've constructed one it will represent a certain point in "real" time. The time zone is only relevant when you want to convert that abstract time point into a human-readable string.

一旦你构建了一个,它将在“实时”中代表一个特定的点。只有当您想要将抽象的时间点转换为人类可读的字符串时,时区才具有相关性。

Thus it makes sense you would only be able to change the actual time the Date represents in the constructor. Sadly it seems that there is no way to pass in an explicit timezone - and the constructor you are calling (arguably correctly) translates your "local" time variables into GMT when it stores them canonically - so there is no way to use the int, int, int constructor for GMT times.

因此,只有在构造函数中更改日期表示的实际时间才有意义。可悲的是,似乎没有办法通过显式的时区,你调用的构造函数(可以说是正确的)将你的“本地”时间变量转换为格林尼治时间当它存储他们正规的,所以没有办法使用int,int,int构造函数对GMT时间。

On the plus side, it's trivial to just use the constructor that takes a String instead. You don't even have to convert the numeric month into a String (on Firefox at least), so I was hoping a naive implementation would work. However, after trying it out it works successfully in Firefox, Chrome, and Opera but fails in Konqueror ("Invalid Date") , Safari ("Invalid Date") and IE ("NaN"). I suppose you'd just have a lookup array to convert the month to a string, like so:

从好的方面来说,仅仅使用带字符串的构造函数是很简单的。您甚至不需要将数字月转换为字符串(至少在Firefox上),所以我希望一个简单的实现可以工作。然而,在试用之后,它在Firefox、Chrome和Opera上都成功运行,但在Konqueror(“无效日期”)、Safari(“无效日期”)和IE(“NaN”)上都失败了。我想您只需使用一个查找数组将月份转换为字符串,如下所示:

var months = [ '', 'January', 'February', ..., 'December'];

function createGMTDate(xiYear, xiMonth, xiDate) {
   return new Date(months[xiMonth] + ' ' + xiDate + ', ' + xiYear + ' 00:00:00 GMT');
}

#5


15  

If you want to deal with the slightly different, but related, problem of creating a Javascript Date object from year, month, day, ..., including timezone – that is, if you want to parse a string into a Date – then you apparently have to do an infuriatingly complicated dance:

如果您想处理稍微不同但相关的问题,从年、月、日创建一个Javascript日期对象……,包括时区——也就是说,如果你想把一个字符串解析成一个日期——那么你显然必须跳一种让人恼火的复杂舞蹈:

// parseISO8601String : string -> Date
// Parse an ISO-8601 date, including possible timezone,
// into a Javascript Date object.
//
// Test strings: parseISO8601String(x).toISOString()
// "2013-01-31T12:34"              -> "2013-01-31T12:34:00.000Z"
// "2013-01-31T12:34:56"           -> "2013-01-31T12:34:56.000Z"
// "2013-01-31T12:34:56.78"        -> "2013-01-31T12:34:56.780Z"
// "2013-01-31T12:34:56.78+0100"   -> "2013-01-31T11:34:56.780Z"
// "2013-01-31T12:34:56.78+0530"   -> "2013-01-31T07:04:56.780Z"
// "2013-01-31T12:34:56.78-0330"   -> "2013-01-31T16:04:56.780Z"
// "2013-01-31T12:34:56-0330"      -> "2013-01-31T16:04:56.000Z"
// "2013-01-31T12:34:56Z"          -> "2013-01-31T12:34:56.000Z"
function parseISO8601String(dateString) {
    var timebits = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]*)(\.[0-9]*)?)?(?:([+-])([0-9]{2})([0-9]{2}))?/;
    var m = timebits.exec(dateString);
    var resultDate;
    if (m) {
        var utcdate = Date.UTC(parseInt(m[1]),
                               parseInt(m[2])-1, // months are zero-offset (!)
                               parseInt(m[3]),
                               parseInt(m[4]), parseInt(m[5]), // hh:mm
                               (m[6] && parseInt(m[6]) || 0),  // optional seconds
                               (m[7] && parseFloat(m[7])*1000) || 0); // optional fraction
        // utcdate is milliseconds since the epoch
        if (m[9] && m[10]) {
            var offsetMinutes = parseInt(m[9]) * 60 + parseInt(m[10]);
            utcdate += (m[8] === '+' ? -1 : +1) * offsetMinutes * 60000;
        }
        resultDate = new Date(utcdate);
    } else {
        resultDate = null;
    }
    return resultDate;
}

That is, you create a 'UTC time' using the date without timezone (so you know what locale it's in, namely the UTC 'locale', and it's not defaulted to the local one), and then manually apply the indicated timezone offset.

也就是说,您可以使用没有时区的日期创建一个“UTC时间”(这样您就知道它在什么地区,即UTC“locale”,并且它不会默认为本地时间),然后手动应用指定的时区偏移量。

Wouldn't it have been nice if someone had actually thought about the Javascript date object for more than, oooh, five minutes....

会不会好,如果有人真的想Javascript date对象多,噢,五分钟....

#6


15  

I know this is old but if it helps you could use moment and moment time zone. If you haven't seen them take a look.

我知道这是旧的,但如果它能帮助你利用时间和时间时区。如果你还没见过他们,看看。

http://momentjs.com/timezone/

http://momentjs.com/timezone/

http://momentjs.com/

http://momentjs.com/

two really handy time manipulation libraries.

两个非常方便的时间操作库。

#7


11  

d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));

offset value base on which location time zone you would like to set 
For India offset value +5.5,
New York offset value -4,
London offset value +1

for all location offset Wiki List of UTC time offsets

所有的位置偏移维基列表的UTC时间偏移。

#8


9  

One line solution

一行的解决方案

new Date(new Date(1422524805305).getTime() - 330*60*1000)

Instead of 1422524805305, use the timestamp in milliseconds Instead of 330, use your timezone offset in minutes wrt. GMT (eg India +5:30 is 5*60+30 = 330 minutes)

不要使用1422524805305,使用时间戳(毫秒)而不是330,使用时区偏移(分钟)wrt。格林尼治标准时间(例如印度+5:30是5*60+30 = 330分钟)

#9


7  

This may help someone, put UTC at the end of what you pass in to the new constructor

这可能会帮助某些人,将UTC放在传递给新构造函数的末尾

At least in chrome you can say var date = new Date("2014-01-01 11:00:00 UTC")

至少在chrome中你可以说var date = new date(“2014-01-01 11:00:00 UTC”)

#10


5  

getTimeZoneOffset is minus for UTC + z.

对于UTC + z, getTimeZoneOffset是负的。

var d = new Date(xiYear, xiMonth, xiDate);
if(d.getTimezoneOffset() > 0){
    d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
}

#11


5  

The easiest way that I have found to get the correct date is using datejs.

我发现获得正确日期的最简单方法是使用datejs。

http://www.datejs.com/

http://www.datejs.com/

I get my dates via Ajax in this format as a string: '2016-01-12T00:00:00'

我通过Ajax以字符串形式获取日期:2016-01-12 t00:00

var yourDateString = '2016-01-12T00:00:00';
var yourDate = new Date(yourDateString);
console.log(yourDate);
if (yourDate.getTimezoneOffset() > 0){
    yourDate = new Date(yourDateString).addMinutes(yourDate.getTimezoneOffset());
}
console.log(yourDate);

Console will read:

控制台将读取:

Mon Jan 11 2016 19:00:00 GMT-0500 (Eastern Standard Time)

2016年1月11日星期一19:00:00 GMT-0500(东部标准时间)

Tue Jan 12 2016 00:00:00 GMT-0500 (Eastern Standard Time)

2016年1月12日星期二00:00 GMT-0500(东部标准时间)

https://jsfiddle.net/vp1ena7b/3/

https://jsfiddle.net/vp1ena7b/3/

The 'addMinutes' comes from datejs, you could probably do this in pure js on your own, but I already had datejs in my project so I found a way to use it to get the correct dates.

“addMinutes”来自datejs,您可以自己使用纯js进行此操作,但是我的项目中已经有了datejs,所以我找到了一种使用它来获取正确日期的方法。

I thought that this might help someone...

我想这可能会对某人有所帮助……

#12


2  

any mileage in

任何里程

var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();

#13


2  

This code will return your Date object formatted with the browser timezone.

此代码将返回用浏览器时区格式化的日期对象。

Date.prototype.timezone = function () {
    this.setHours(this.getHours() + (new Date().getTimezoneOffset() / 60));
    return this;
}

#14


1  

Best Solution I have seen from this came from

我看到的最好的解决办法来自于这个

http://www.codingforums.com/archive/index.php/t-19663.html

http://www.codingforums.com/archive/index.php/t - 19663. - html

Print Time Function

打印时间函数

<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)

function printTime(offset) {
    offset++;
    tempDate = new Date()
    tempDate.setTime(UTCDate.getTime()+3600000*(offset))
    timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
    timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
    timeValue += " hrs."
    return timeValue
    }
    var now = new Date()
    var seed = now.getTime() % 0xfffffff
    var same = rand(12)
</script>

Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>

Full Code Example

完整的代码示例

<html>

<head>
<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)

function printTime(offset) {
offset++;
tempDate = new Date()
tempDate.setTime(UTCDate.getTime()+3600000*(offset))
timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
timeValue += " hrs."
return timeValue
}
var now = new Date()
var seed = now.getTime() % 0xfffffff
var same = rand(12)
</script>

</head>

<body>
Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>
<br>
Michigan:
<script language="JavaScript">document.write(printTime("-5"))</script>
<br>
Greenwich, England(UTC):
<script language="JavaScript">document.write(printTime("-0"))</script>
<br>
Tokyo, Japan:
<script language="JavaScript">document.write(printTime("+9"))</script>
<br>
Berlin, Germany:
<script language="JavaScript">document.write(printTime("+1"))</script>

</body>
</html>

#15


0  

I used the timezone-js package.

我使用了timezone-js包。

var timezoneJS  = require('timezone-js');
var tzdata = require('tzdata');

: :

::

createDate(dateObj) {
    if ( dateObj == null ) {
        return null;
    }
    var nativeTimezoneOffset = new Date().getTimezoneOffset();
    var offset = this.getTimeZoneOffset();

    // use the native Date object if the timezone matches
    if ( offset == -1 * nativeTimezoneOffset ) {
        return dateObj;
    }

    this.loadTimeZones();

    // FIXME: it would be better if timezoneJS.Date was an instanceof of Date
    //        tried jquery $.extend
    //        added hack to Fiterpickr to look for Dater.getTime instead of "d instanceof Date"
    return new timezoneJS.Date(dateObj,this.getTimeZoneName());
},

#16


0  

This worked for me. Not sure if it is a good idea though.

这为我工作。但我不确定这是不是一个好主意。

var myDate = new Date();
console.log('myDate:', myDate);   // myDate: "2018-04-04T01:09:38.112Z"

var offset = '+5';  // e.g. if the timeZone is -5

var MyDateWithOffset = new Date( myDate.toGMTString() + offset );   

console.log('MyDateWithOffset:', MyDateWithOffset); // myDateWithOffset: "2018-04-03T20:09:38.000Z"

#17


-5  

This is BEST solution

这是最好的解决方案

Using:

使用:

// TO ALL dates
Date.timezoneOffset(-240) // +4 UTC

// Override offset only for THIS date
new Date().timezoneOffset(-180) // +3 UTC

Code:

代码:

Date.prototype.timezoneOffset = new Date().getTimezoneOffset();

Date.setTimezoneOffset = function(timezoneOffset) {
  return this.prototype.timezoneOffset = timezoneOffset;
};

Date.getTimezoneOffset = function() {
  return this.prototype.timezoneOffset;
};

Date.prototype.setTimezoneOffset = function(timezoneOffset) {
  return this.timezoneOffset = timezoneOffset;
};

Date.prototype.getTimezoneOffset = function() {
  return this.timezoneOffset;
};

Date.prototype.toString = function() {
  var offsetDate, offsetTime;
  offsetTime = this.timezoneOffset * 60 * 1000;
  offsetDate = new Date(this.getTime() - offsetTime);
  return offsetDate.toUTCString();
};

['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear', 'Year', 'Day'].forEach((function(_this) {
  return function(key) {
    Date.prototype["get" + key] = function() {
      var offsetDate, offsetTime;
      offsetTime = this.timezoneOffset * 60 * 1000;
      offsetDate = new Date(this.getTime() - offsetTime);
      return offsetDate["getUTC" + key]();
    };
    return Date.prototype["set" + key] = function(value) {
      var offsetDate, offsetTime, time;
      offsetTime = this.timezoneOffset * 60 * 1000;
      offsetDate = new Date(this.getTime() - offsetTime);
      offsetDate["setUTC" + key](value);
      time = offsetDate.getTime() + offsetTime;
      this.setTime(time);
      return time;
    };
  };
})(this));

Coffee version:

咖啡版本:

Date.prototype.timezoneOffset = new Date().getTimezoneOffset()


Date.setTimezoneOffset = (timezoneOffset)->
    return @prototype.timezoneOffset = timezoneOffset


Date.getTimezoneOffset = ->
    return @prototype.timezoneOffset


Date.prototype.setTimezoneOffset = (timezoneOffset)->
    return @timezoneOffset = timezoneOffset


Date.prototype.getTimezoneOffset = ->
    return @timezoneOffset


Date.prototype.toString = ->
    offsetTime = @timezoneOffset * 60 * 1000
    offsetDate = new Date(@getTime() - offsetTime)
    return offsetDate.toUTCString()


[
    'Milliseconds', 'Seconds', 'Minutes', 'Hours',
    'Date', 'Month', 'FullYear', 'Year', 'Day'
]
.forEach (key)=>
    Date.prototype["get#{key}"] = ->
        offsetTime = @timezoneOffset * 60 * 1000
        offsetDate = new Date(@getTime() - offsetTime)
        return offsetDate["getUTC#{key}"]()

    Date.prototype["set#{key}"] = (value)->
        offsetTime = @timezoneOffset * 60 * 1000
        offsetDate = new Date(@getTime() - offsetTime)
        offsetDate["setUTC#{key}"](value)
        time = offsetDate.getTime() + offsetTime
        @setTime(time)
        return time

#1


407  

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

使用. setutchours()可以在utctime中设置日期,这将允许您在整个系统中使用UTC-times。

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

但是,除非指定日期字符串,否则不能在构造函数中使用UTC设置它。

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

使用新的日期(日期。UTC(年、月、日、小时、分钟、秒)您可以从特定的UTC时间创建一个日期对象。

#2


166  

var d = new Date(xiYear, xiMonth, xiDate);
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );

When this date object is deserialized, you might get the information you expect.

当这个日期对象被反序列化时,您可能会得到您期望的信息。

#3


122  

I believe you need the createDateAsUTC function (please compare with convertDateToUTC)

我相信您需要createDateAsUTC函数(请与convertDateToUTC进行比较)

function createDateAsUTC(date) {
    return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
}

function convertDateToUTC(date) { 
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()); 
}

#4


23  

I don't believe this is possible - there is no ability to set the timezone on a Date object after it is created.

我认为这是不可能的——在创建日期对象之后,没有能力对其设置时区。

And in a way this makes sense - conceptually (if perhaps not in implementation); per http://en.wikipedia.org/wiki/Unix_timestamp (emphasis mine):

在某种程度上,这是有意义的——从概念上来说(如果不是在实施中);我每http://en.wikipedia.org/wiki/Unix_timestamp(重点):

Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970.

Unix时间(POSIX time)是一个系统,用于描述时间上的瞬间,定义为自1970年1月1日星期四午夜协调世界时(UTC)以来的秒数。

Once you've constructed one it will represent a certain point in "real" time. The time zone is only relevant when you want to convert that abstract time point into a human-readable string.

一旦你构建了一个,它将在“实时”中代表一个特定的点。只有当您想要将抽象的时间点转换为人类可读的字符串时,时区才具有相关性。

Thus it makes sense you would only be able to change the actual time the Date represents in the constructor. Sadly it seems that there is no way to pass in an explicit timezone - and the constructor you are calling (arguably correctly) translates your "local" time variables into GMT when it stores them canonically - so there is no way to use the int, int, int constructor for GMT times.

因此,只有在构造函数中更改日期表示的实际时间才有意义。可悲的是,似乎没有办法通过显式的时区,你调用的构造函数(可以说是正确的)将你的“本地”时间变量转换为格林尼治时间当它存储他们正规的,所以没有办法使用int,int,int构造函数对GMT时间。

On the plus side, it's trivial to just use the constructor that takes a String instead. You don't even have to convert the numeric month into a String (on Firefox at least), so I was hoping a naive implementation would work. However, after trying it out it works successfully in Firefox, Chrome, and Opera but fails in Konqueror ("Invalid Date") , Safari ("Invalid Date") and IE ("NaN"). I suppose you'd just have a lookup array to convert the month to a string, like so:

从好的方面来说,仅仅使用带字符串的构造函数是很简单的。您甚至不需要将数字月转换为字符串(至少在Firefox上),所以我希望一个简单的实现可以工作。然而,在试用之后,它在Firefox、Chrome和Opera上都成功运行,但在Konqueror(“无效日期”)、Safari(“无效日期”)和IE(“NaN”)上都失败了。我想您只需使用一个查找数组将月份转换为字符串,如下所示:

var months = [ '', 'January', 'February', ..., 'December'];

function createGMTDate(xiYear, xiMonth, xiDate) {
   return new Date(months[xiMonth] + ' ' + xiDate + ', ' + xiYear + ' 00:00:00 GMT');
}

#5


15  

If you want to deal with the slightly different, but related, problem of creating a Javascript Date object from year, month, day, ..., including timezone – that is, if you want to parse a string into a Date – then you apparently have to do an infuriatingly complicated dance:

如果您想处理稍微不同但相关的问题,从年、月、日创建一个Javascript日期对象……,包括时区——也就是说,如果你想把一个字符串解析成一个日期——那么你显然必须跳一种让人恼火的复杂舞蹈:

// parseISO8601String : string -> Date
// Parse an ISO-8601 date, including possible timezone,
// into a Javascript Date object.
//
// Test strings: parseISO8601String(x).toISOString()
// "2013-01-31T12:34"              -> "2013-01-31T12:34:00.000Z"
// "2013-01-31T12:34:56"           -> "2013-01-31T12:34:56.000Z"
// "2013-01-31T12:34:56.78"        -> "2013-01-31T12:34:56.780Z"
// "2013-01-31T12:34:56.78+0100"   -> "2013-01-31T11:34:56.780Z"
// "2013-01-31T12:34:56.78+0530"   -> "2013-01-31T07:04:56.780Z"
// "2013-01-31T12:34:56.78-0330"   -> "2013-01-31T16:04:56.780Z"
// "2013-01-31T12:34:56-0330"      -> "2013-01-31T16:04:56.000Z"
// "2013-01-31T12:34:56Z"          -> "2013-01-31T12:34:56.000Z"
function parseISO8601String(dateString) {
    var timebits = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]*)(\.[0-9]*)?)?(?:([+-])([0-9]{2})([0-9]{2}))?/;
    var m = timebits.exec(dateString);
    var resultDate;
    if (m) {
        var utcdate = Date.UTC(parseInt(m[1]),
                               parseInt(m[2])-1, // months are zero-offset (!)
                               parseInt(m[3]),
                               parseInt(m[4]), parseInt(m[5]), // hh:mm
                               (m[6] && parseInt(m[6]) || 0),  // optional seconds
                               (m[7] && parseFloat(m[7])*1000) || 0); // optional fraction
        // utcdate is milliseconds since the epoch
        if (m[9] && m[10]) {
            var offsetMinutes = parseInt(m[9]) * 60 + parseInt(m[10]);
            utcdate += (m[8] === '+' ? -1 : +1) * offsetMinutes * 60000;
        }
        resultDate = new Date(utcdate);
    } else {
        resultDate = null;
    }
    return resultDate;
}

That is, you create a 'UTC time' using the date without timezone (so you know what locale it's in, namely the UTC 'locale', and it's not defaulted to the local one), and then manually apply the indicated timezone offset.

也就是说,您可以使用没有时区的日期创建一个“UTC时间”(这样您就知道它在什么地区,即UTC“locale”,并且它不会默认为本地时间),然后手动应用指定的时区偏移量。

Wouldn't it have been nice if someone had actually thought about the Javascript date object for more than, oooh, five minutes....

会不会好,如果有人真的想Javascript date对象多,噢,五分钟....

#6


15  

I know this is old but if it helps you could use moment and moment time zone. If you haven't seen them take a look.

我知道这是旧的,但如果它能帮助你利用时间和时间时区。如果你还没见过他们,看看。

http://momentjs.com/timezone/

http://momentjs.com/timezone/

http://momentjs.com/

http://momentjs.com/

two really handy time manipulation libraries.

两个非常方便的时间操作库。

#7


11  

d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));

offset value base on which location time zone you would like to set 
For India offset value +5.5,
New York offset value -4,
London offset value +1

for all location offset Wiki List of UTC time offsets

所有的位置偏移维基列表的UTC时间偏移。

#8


9  

One line solution

一行的解决方案

new Date(new Date(1422524805305).getTime() - 330*60*1000)

Instead of 1422524805305, use the timestamp in milliseconds Instead of 330, use your timezone offset in minutes wrt. GMT (eg India +5:30 is 5*60+30 = 330 minutes)

不要使用1422524805305,使用时间戳(毫秒)而不是330,使用时区偏移(分钟)wrt。格林尼治标准时间(例如印度+5:30是5*60+30 = 330分钟)

#9


7  

This may help someone, put UTC at the end of what you pass in to the new constructor

这可能会帮助某些人,将UTC放在传递给新构造函数的末尾

At least in chrome you can say var date = new Date("2014-01-01 11:00:00 UTC")

至少在chrome中你可以说var date = new date(“2014-01-01 11:00:00 UTC”)

#10


5  

getTimeZoneOffset is minus for UTC + z.

对于UTC + z, getTimeZoneOffset是负的。

var d = new Date(xiYear, xiMonth, xiDate);
if(d.getTimezoneOffset() > 0){
    d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
}

#11


5  

The easiest way that I have found to get the correct date is using datejs.

我发现获得正确日期的最简单方法是使用datejs。

http://www.datejs.com/

http://www.datejs.com/

I get my dates via Ajax in this format as a string: '2016-01-12T00:00:00'

我通过Ajax以字符串形式获取日期:2016-01-12 t00:00

var yourDateString = '2016-01-12T00:00:00';
var yourDate = new Date(yourDateString);
console.log(yourDate);
if (yourDate.getTimezoneOffset() > 0){
    yourDate = new Date(yourDateString).addMinutes(yourDate.getTimezoneOffset());
}
console.log(yourDate);

Console will read:

控制台将读取:

Mon Jan 11 2016 19:00:00 GMT-0500 (Eastern Standard Time)

2016年1月11日星期一19:00:00 GMT-0500(东部标准时间)

Tue Jan 12 2016 00:00:00 GMT-0500 (Eastern Standard Time)

2016年1月12日星期二00:00 GMT-0500(东部标准时间)

https://jsfiddle.net/vp1ena7b/3/

https://jsfiddle.net/vp1ena7b/3/

The 'addMinutes' comes from datejs, you could probably do this in pure js on your own, but I already had datejs in my project so I found a way to use it to get the correct dates.

“addMinutes”来自datejs,您可以自己使用纯js进行此操作,但是我的项目中已经有了datejs,所以我找到了一种使用它来获取正确日期的方法。

I thought that this might help someone...

我想这可能会对某人有所帮助……

#12


2  

any mileage in

任何里程

var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();

#13


2  

This code will return your Date object formatted with the browser timezone.

此代码将返回用浏览器时区格式化的日期对象。

Date.prototype.timezone = function () {
    this.setHours(this.getHours() + (new Date().getTimezoneOffset() / 60));
    return this;
}

#14


1  

Best Solution I have seen from this came from

我看到的最好的解决办法来自于这个

http://www.codingforums.com/archive/index.php/t-19663.html

http://www.codingforums.com/archive/index.php/t - 19663. - html

Print Time Function

打印时间函数

<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)

function printTime(offset) {
    offset++;
    tempDate = new Date()
    tempDate.setTime(UTCDate.getTime()+3600000*(offset))
    timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
    timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
    timeValue += " hrs."
    return timeValue
    }
    var now = new Date()
    var seed = now.getTime() % 0xfffffff
    var same = rand(12)
</script>

Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>

Full Code Example

完整的代码示例

<html>

<head>
<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)

function printTime(offset) {
offset++;
tempDate = new Date()
tempDate.setTime(UTCDate.getTime()+3600000*(offset))
timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
timeValue += " hrs."
return timeValue
}
var now = new Date()
var seed = now.getTime() % 0xfffffff
var same = rand(12)
</script>

</head>

<body>
Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>
<br>
Michigan:
<script language="JavaScript">document.write(printTime("-5"))</script>
<br>
Greenwich, England(UTC):
<script language="JavaScript">document.write(printTime("-0"))</script>
<br>
Tokyo, Japan:
<script language="JavaScript">document.write(printTime("+9"))</script>
<br>
Berlin, Germany:
<script language="JavaScript">document.write(printTime("+1"))</script>

</body>
</html>

#15


0  

I used the timezone-js package.

我使用了timezone-js包。

var timezoneJS  = require('timezone-js');
var tzdata = require('tzdata');

: :

::

createDate(dateObj) {
    if ( dateObj == null ) {
        return null;
    }
    var nativeTimezoneOffset = new Date().getTimezoneOffset();
    var offset = this.getTimeZoneOffset();

    // use the native Date object if the timezone matches
    if ( offset == -1 * nativeTimezoneOffset ) {
        return dateObj;
    }

    this.loadTimeZones();

    // FIXME: it would be better if timezoneJS.Date was an instanceof of Date
    //        tried jquery $.extend
    //        added hack to Fiterpickr to look for Dater.getTime instead of "d instanceof Date"
    return new timezoneJS.Date(dateObj,this.getTimeZoneName());
},

#16


0  

This worked for me. Not sure if it is a good idea though.

这为我工作。但我不确定这是不是一个好主意。

var myDate = new Date();
console.log('myDate:', myDate);   // myDate: "2018-04-04T01:09:38.112Z"

var offset = '+5';  // e.g. if the timeZone is -5

var MyDateWithOffset = new Date( myDate.toGMTString() + offset );   

console.log('MyDateWithOffset:', MyDateWithOffset); // myDateWithOffset: "2018-04-03T20:09:38.000Z"

#17


-5  

This is BEST solution

这是最好的解决方案

Using:

使用:

// TO ALL dates
Date.timezoneOffset(-240) // +4 UTC

// Override offset only for THIS date
new Date().timezoneOffset(-180) // +3 UTC

Code:

代码:

Date.prototype.timezoneOffset = new Date().getTimezoneOffset();

Date.setTimezoneOffset = function(timezoneOffset) {
  return this.prototype.timezoneOffset = timezoneOffset;
};

Date.getTimezoneOffset = function() {
  return this.prototype.timezoneOffset;
};

Date.prototype.setTimezoneOffset = function(timezoneOffset) {
  return this.timezoneOffset = timezoneOffset;
};

Date.prototype.getTimezoneOffset = function() {
  return this.timezoneOffset;
};

Date.prototype.toString = function() {
  var offsetDate, offsetTime;
  offsetTime = this.timezoneOffset * 60 * 1000;
  offsetDate = new Date(this.getTime() - offsetTime);
  return offsetDate.toUTCString();
};

['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear', 'Year', 'Day'].forEach((function(_this) {
  return function(key) {
    Date.prototype["get" + key] = function() {
      var offsetDate, offsetTime;
      offsetTime = this.timezoneOffset * 60 * 1000;
      offsetDate = new Date(this.getTime() - offsetTime);
      return offsetDate["getUTC" + key]();
    };
    return Date.prototype["set" + key] = function(value) {
      var offsetDate, offsetTime, time;
      offsetTime = this.timezoneOffset * 60 * 1000;
      offsetDate = new Date(this.getTime() - offsetTime);
      offsetDate["setUTC" + key](value);
      time = offsetDate.getTime() + offsetTime;
      this.setTime(time);
      return time;
    };
  };
})(this));

Coffee version:

咖啡版本:

Date.prototype.timezoneOffset = new Date().getTimezoneOffset()


Date.setTimezoneOffset = (timezoneOffset)->
    return @prototype.timezoneOffset = timezoneOffset


Date.getTimezoneOffset = ->
    return @prototype.timezoneOffset


Date.prototype.setTimezoneOffset = (timezoneOffset)->
    return @timezoneOffset = timezoneOffset


Date.prototype.getTimezoneOffset = ->
    return @timezoneOffset


Date.prototype.toString = ->
    offsetTime = @timezoneOffset * 60 * 1000
    offsetDate = new Date(@getTime() - offsetTime)
    return offsetDate.toUTCString()


[
    'Milliseconds', 'Seconds', 'Minutes', 'Hours',
    'Date', 'Month', 'FullYear', 'Year', 'Day'
]
.forEach (key)=>
    Date.prototype["get#{key}"] = ->
        offsetTime = @timezoneOffset * 60 * 1000
        offsetDate = new Date(@getTime() - offsetTime)
        return offsetDate["getUTC#{key}"]()

    Date.prototype["set#{key}"] = (value)->
        offsetTime = @timezoneOffset * 60 * 1000
        offsetDate = new Date(@getTime() - offsetTime)
        offsetDate["setUTC#{key}"](value)
        time = offsetDate.getTime() + offsetTime
        @setTime(time)
        return time