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

2009-1-1 to 2009-1-3

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

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

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

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


当前回答

如果您的日期上有时区,则可以使用date fns tz:

import { zonedTimeToUtc } from 'date-fns-tz';

const dateBrazil = new Date() // I'm in Brazil, you should have or get the user timezone.
const dateUtc = zonedTimeToUtc(dateBrazil, 'America/Sao_Paulo')

其他回答

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

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

$.parseDate('yy-mm-dd', '2007-01-26');
var myDate = new Date(); // Set this to your date in whichever timezone.
var utcDate = myDate.toUTCString();
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”而不是用户的时区偏移。

这是我过去所做的:

var utcDateString = new Date(new Date().toUTCString()).toISOString();