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

2009-1-1 to 2009-1-3

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

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

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

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


当前回答

我发现jQuery全球化插件的日期解析工作得最好。其他方法存在跨浏览器问题,像date.js这样的东西已经很长时间没有更新了。

页面上也不需要datePicker。您可以调用与文档中给出的示例类似的内容:

$.parseDate('yy-mm-dd', '2007-01-26');

其他回答

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

我会制作一个函数来实现这一点,尽管有点争议,但还是将其添加到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”而不是用户的时区偏移。

const event = new Date();

console.log(event.toUTCString());

转换为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链接

对于目标是将其作为“日期对象”而不是字符串获取的其他人,并且您只想显示不带TZ(可能是硬编码的)的日期/时间,您可以做的是:

const now = new Date();
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
const day = now.getUTCDate();
const hour = now.getUTCHours();

const tomorrowUTC= new Date();
tomorrowUTC.setDate(day + 1); // +1 because my logic is to get "tomorrow"
tomorrowUTC.setYear(year);
tomorrowUTC.setMonth(month);
tomorrowUTC.Hours(hour);

// then use the tomorrowUTC for to display/format it
// tomorrowUTC is a "Date" and not a string.

然后,您可以执行以下操作:

我们将在${格式(明天UTC,'EEEE do MMMM hh:mmaa')}UTC删除您的帐户

(格式是一个日期fns函数,如果需要,可以使用其他lib);

这有点“黑客”,因为这仍然使用本地时区,但如果你只想显示日期而不是时区,那么这就可以了。

var myDate = new Date(); // Set this to your date in whichever timezone.
var utcDate = myDate.toUTCString();