Convert date and time to UTC(将日期和时间转换为UTC)
本文介绍了将日期和时间转换为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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:将日期和时间转换为UTC


猜你喜欢
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06