javascript - 将日期和时间转换为 UTC

标签 javascript datetime momentjs datetime-format

我要求用户在我的应用程序中输入日期和时间。用户将根据他们所在的时区输入时间。当我将此日期和时间保存到数据库时,我想将时间转换为 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();

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

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

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

最佳答案

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

JavaScript Date Reference

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)

例如,

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

更新:示例(包括 .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)

关于javascript - 将日期和时间转换为 UTC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37117374/

相关文章:

javascript - 使用 jQuery slide/animate 从右侧在 div 中滑动时将居中元素向左移动

javascript - Jquery 历史记录/后退按钮插件的当前状态?

python - 如何使用 Python 将 LabVIEW 十进制日期转换为字符串日期时间格式?

c# - 将时间戳附加到文件名

momentjs - 使用 Moment.js 获取序号

javascript - 定期更新 firebase 条目

node.js - 如何将当前日期与数据库中的日期进行比较

php - 可以安全弹出登录吗?

javascript - 如何将相同的元素添加到javascript数组n次

ruby-on-rails - Ruby/Rails 如何在 DateTime 范围内迭代月份?