将日期和时间转换为 UTC

eri*_*n30 0 javascript datetime datetime-format momentjs

我要求用户在我的应用程序中输入日期和时间。用户将根据他们所在的时区输入时间。当我将此日期和时间保存到数据库时,我想将时间转换为 UTC,这样当我按时间查询(以 UTC 完成)时,我可以找到条目。

这就是我目前所做的:

var date = new Date();
var dateString = "0" + (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time;
//format date
date = moment(dateString, "MM/DD/YYYY HH:mm a");
date = new Date(date).toISOString();
Run Code Online (Sandbox Code Playgroud)

其中 time 是用户输入的时间(例如,如果我想在上午 11:00 安排某项活动,则时间 = 11:00am)

当它保存到数据库时,它看起来像 : ISODate("2016-05-09T11:00:00Z")这是不正确的,因为这是保存为祖鲁时间的 EST。

如何将时间(我正在使用时刻)转换为正确的祖鲁时间?

Won*_*rub 5

一种选择是使用 Javascript 的内置 UTC 函数。

JavaScript 日期参考

getUTCDate() - Returns the day of the month, according to universal time (from 1-31)
getUTCDay() - Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear()- Returns the year, according to universal time
getUTCHours() - Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds() - Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes() - Returns the minutes, according to universal time (from 0-59)
getUTCMonth() - Returns the month, according to universal time (from 0-11)
getUTCSeconds() - Returns the seconds, according to universal time (from 0-59)
Run Code Online (Sandbox Code Playgroud)

例如,

new Date('2016-05-09 10:00:00')
    returns Mon May 09 2016 10:00:00 GMT-0400

new Date('2016-05-09 10:00:00').getUTCHours()
    returns 14
Run Code Online (Sandbox Code Playgroud)

更新:示例(包括 .toISOString())

如果我们选择东部时间 2016 年 7 月 4 日@ 8:00 PM (GMT-0400),则 UTC 将为 2016 年 7 月 5 日@ 00:00(午夜):

var date = new Date('2016-07-04 20:00:00')
date.getUTCFullYear = 2016
date.getUTCMonth = 6 (0 base)
date.getUTCDate = 5
date.getUTCHours = 0
date.getUTCMinutes = 0

var date = new Date('2016-07-04 20:00:00')
date.toISOString() = "2016-07-05T00:00:00.000Z" (UTC)
Run Code Online (Sandbox Code Playgroud)