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

2009-1-1 to 2009-1-3

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

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

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

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


当前回答

date = '2012-07-28'; stringdate = new Date(date).toISOString();

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

其他回答

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

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();
}

getTimezoneOffset()方法返回时区差异,以分钟,从当前区域设置(主机系统设置)到UTC。

来源:MDN网络文档

这意味着,如果本地时区晚于UTC,则偏移量为正,如果超前,则偏移为负。例如,对于时区UTC+02:00,将返回-120。

let d=新日期();console.log(d);d.setTime(d.getTime()+(d.getTimezoneOffset()*60000));console.log(d);

注意:这会将日期对象时间转换为UTC±00:00,而不会转换其时区,因此日期对象时区仍然相同,但值将为UTC±0:00。

甚至更简单

myvar.setTime(myvar.getTime() + myvar.getTimezoneOffset() * 60000);

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

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

使用moment.js UTC方法;

const moment = require('moment');
const utc = moment.utc(new Date(string));