我要求用户在我的应用程序中输入日期和时间。用户将根据他们所在的时区输入时间。当我将此日期和时间保存到数据库中时,我想将时间转换为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 am安排时间,则时间= 11:00 am)
将其保存到数据库后,它看起来像:ISODate("2016-05-09T11:00:00Z")
是不正确的,因为这是保存为Zulu时间的EST。
如何转换时间(我使用的是矩)保存为正确的祖鲁时间?
一种选择是使用Javascript的内置UTC函数。
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日美国东部时间(GMT-0400)8:00 PM,那么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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句