假设您网站的用户输入了一个日期范围。

2009-1-1 to 2009-1-3

您需要将此日期发送到服务器进行某些处理,但服务器要求所有日期和时间均为UTC。

现在假设用户在阿拉斯加。由于它们所处的时区与UTC完全不同,因此需要将日期范围转换为如下所示:

2009-1-1T8:00:00 to 2009-1-4T7:59:59

使用JavaScriptDate对象,如何将第一个“本地化”日期范围转换为服务器能够理解的内容?


当前回答

我刚刚发现Steven Levithan的date.format.js的1.2.3版本正是我想要的。它允许您为JavaScript日期提供格式字符串,并将从本地时间转换为UTC。下面是我现在使用的代码:

// JavaScript dates don't like hyphens!    
var rectifiedDateText = dateText.replace(/-/g, "/");
var d = new Date(rectifiedDateText);

// Using a predefined mask from date.format.js.
var convertedDate = dateFormat(d, 'isoUtcDateTime'); 

其他回答

如果你经常与日期打交道,那么使用moment.js是值得的(http://momentjs.com). 转换为UTC的方法为:

moment(yourTime).utc()

您可以使用格式将日期更改为所需的任何格式:

moment(yourTime).utc().format("YYYY-MM-DD")

当前也有偏移选项,但有一个额外的补充库用于处理时区(http://momentjs.com/timezone/). 时间转换如下所示:

moment.tz(yourUTCTime, "America/New_York")
date = '2012-07-28'; stringdate = new Date(date).toISOString();

应该可以在大多数更新的浏览器中工作。在Firefox 6.0上返回2012-07-28T00:00:00.000Z

你想把日期转换成这样的字符串吗?

我会制作一个函数来实现这一点,尽管有点争议,但还是将其添加到Date原型中。如果你不习惯这样做,那么你可以把它作为一个独立的函数,把日期作为一个参数传递。

Date.prototype.getISOString = function() {
    var zone = '', temp = -this.getTimezoneOffset() / 60 * 100;
    if (temp >= 0) zone += "+";
    zone += (Math.abs(temp) < 100 ? "00" : (Math.abs(temp) < 1000 ? "0" : "")) + temp;

    // "2009-6-4T14:7:32+10:00"
    return this.getFullYear()   // 2009
         + "-"
         + (this.getMonth() + 1) // 6
         + "-"
         + this.getDate()       // 4
         + "T"
         + this.getHours()      // 14
         + ":"
         + this.getMinutes()    // 7
         + ":"
         + this.getSeconds()    // 32
         + zone.substr(0, 3)    // +10
         + ":"
         + String(temp).substr(-2) // 00
    ;
};

如果您在UTC时间需要它,只需使用getUTC*替换所有get*函数,例如:getUTCFullYear、getUTCMonth、getUTCHours。。。然后在末尾添加“+00:00”而不是用户的时区偏移。

所以这是我必须要做的,因为我仍然希望JavaScript日期对象作为日期进行操作,而不幸的是,这些答案中的很多都需要您转到字符串。

//First i had a string called stringDateVar that i needed to convert to Date
var newDate = new Date(stringDateVar)

//output: 2019-01-07T04:00:00.000Z
//I needed it 2019-01-07T00:00:00.000Z because i had other logic that was dependent on that 

var correctDate = new Date(newDate.setUTCHours(0))

//This will output 2019-01-07T00:00:00.000Z on everything which allows scalability 

转换为ISO而不更改日期/时间

var now = new Date(); // Fri Feb 20 2015 19:29:31 GMT+0530 (India Standard Time) 
var isoDate = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
//OUTPUT : 2015-02-20T19:29:31.238Z

转换为ISO并更改日期/时间(日期/时间将更改)

isoDate = new Date(now).toISOString();
//OUTPUT : 2015-02-20T13:59:31.238Z 

Fiddle链接