【问题标题】:Convert date and time to UTC将日期和时间转换为 UTC
【发布时间】:2016-05-09 13:43:58
【问题描述】:

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


【解决方案1】:

一种选择是使用 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)

【讨论】:

  • 这并不能真正帮助我将时间输入转换为 UTC 时间......这允许我以 UTC 获得当前时间......但如果用户输入 11:00am 获取 UTC hours 只是 UTC 中的当前时间
  • 对不起。可能我没看懂这个问题。如果用户输入未来的日期和时间(假设是一个调度过程),您可以从该输入创建一个 Date 对象。例如,7 月 4 日晚上 8:00 将是“var date = new Date('2016-07-04 20:00:00')”。如果我使用这些函数,我可以让每个 UTC 组件基于 UTC 创建一个新的 Date 对象。根据其他 cmets,当您是有效的 Date 对象时, .toISOString() 也可以使用。我会用例子更新我的答案。
  • 我只是在解析一个字符串输入并从中创建一个日期。因此,如果用户输入 8:00pm 我得到字符串 8:00pm 并需要将其转换为 UTC
  • 我能够使用时刻时区解决我的问题。但你的小提琴也有效。将标记正确
  • 谢谢。很高兴您找到了解决方案。
【解决方案2】:

为了解决这个问题,我使用了 moment-timezone 库。

我首先在服务器上设置时区,因为它只会被 EST 访问:

moment.tz.setDefault("America/New_York");

然后我需要做的就是将时刻对象上的时区设置为 UTC:

date = moment(dateString, "MM/DD/YYYY HH:mm a").tz("UTC");

这成功地将时间从 EST 转换为 UTC

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2011-01-06
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    相关资源
    最近更新 更多