将日期和时间转换为UTC [英] Convert date and time to UTC

查看:44
本文介绍了将日期和时间转换为UTC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

其中,time是用户输入的时间(例如,如果我要将某个时间安排在11:00am,则time=11:00am)

将其保存到数据库时,它看起来如下所示: ISODate("2016-05-09T11:00:00Z")这是不正确的,因为这是另存为Zulu时间的EST。

如何将时间(我正在使用Moment)转换为正确的Zulu时间?

推荐答案

一个选项是使用Java脚本的内置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东部时间(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)

这篇关于将日期和时间转换为UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆