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

2009-1-1 to 2009-1-3

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

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

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

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


当前回答

使用moment包,您可以轻松地将UTC的日期字符串转换为新的date对象:

const moment = require('moment');
let b = new Date(moment.utc('2014-02-20 00:00:00.000000'));
let utc = b.toUTCString();
b.getTime();

当您的服务器不支持时区,并且您希望将UTC日期始终存储在服务器中,并将其作为新的日期对象取回时,这特别有用。以上代码适用于我的需求,也适用于本线程的类似问题。在这里分享,这样可以帮助其他人。我在任何答案中都看不到上述解决方案。谢谢

其他回答

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

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

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

您可以使用以下方法将任何js日期转换为UTC:

let date = new Date(YOUR_DATE).toISOString()

// It would give the date in format "2020-06-16T12:30:00.000Z" where Part before T is date in YYYY-MM-DD format, part after T is time in format HH:MM:SS  and Z stands for UTC - Zero hour offset

toISOString()方法返回简化扩展ISO格式的字符串格式(ISO 8601),总是24或27个字符长(YYYY-MM-DDTH:MM:ss.sssZ或±YYYY-MM-dDTH:MM:ss.sssZ,分别)。时区始终为零UTC偏移,如后缀“Z”。

来源:MDN网络文档

您需要的格式是用.toISOString()方法创建的。对于本机不支持此方法的旧浏览器(ie8及以下版本),可以在此处找到垫片:

这将使您能够执行所需的操作:

var isoDateString=新日期().toISOString();console.log(isoDateString);

对于时区工作,moment.js和moment.jstimezone是非常宝贵的工具。。。特别是用于在客户端和服务器javascript之间导航时区。