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

2009-1-1 to 2009-1-3

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

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

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

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


当前回答

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

其他回答

根据我的观察,

var timeUtc=新日期();

timeUtc将始终显示UTC时间,但如果您调试或控制台,浏览器将始终显示当前时区的时间。

如果您将timeUtc作为参数发送到任何post请求,那么在chrome的网络选项卡中,您可以检查post数据,您将看到timeUtc将具有UTC时间。

如果你经常与日期打交道,那么使用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")

对于目标是将其作为“日期对象”而不是字符串获取的其他人,并且您只想显示不带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);

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

这个功能对我来说非常有用。

function ParseDateForSave(dateValue) {
    // create a new date object
    var newDate = new Date(parseInt(dateValue.substr(6)));

    // return the UTC version of the date
    return newDate.toISOString();
}

扩展功能:

if (!Date.prototype.toUTC){
    Date.prototype.toUTC = function(){
        var utcOffset = new Date().getTimezoneOffset();
        var utcNow    = new Date().addMinutes(utcOffset);
        return utcNow;
    };
}

用法:

new Date().toUTC();