【问题标题】:Java - getting consistent UTC values irrespective of serverJava - 无论服务器如何,都获得一致的 UTC 值
【发布时间】:2013-08-27 19:31:27
【问题描述】:

我正在开发将由印度用户使用的产品版本,我在印度 (GMT+5:30) 工作。我们的服务器在美国。将应用一些具有开始日期和结束日期的方案(例如 - 从 8 月 1 日 00:00:00 到 8 月 31 日 11:59:59,它必须处于活动状态)。 我正在使用http://www.ruddwire.com/handy-code/date-to-millisecond-calculators/ 我使用此代码假设 getTime 将具有一致的 UTC 时间-

// dateStr is what user enters on UI like 1/08/2013 format = dd/MM/yyyy
public static long getUTCDateWithFormat(String dateStr, String format) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    Date date = sdf.parse(dateStr);
    return date.getTime();
}

所以考虑开始时间,当我从 localhost 运行时,对于 8 月 1 日,我得到的结果 = 1375295400000,这意味着 Thu Aug 01 2013 00:00:00 GMT+0530(印度标准时间)。 (所以我知道从 UTC 中减去 5 小时 30 分钟毫秒,因为在运行时我必须将系统时间与这个值进行比较。)

从服务器(美国)运行时预计会保存类似的 UTC,但它保存了 1375336800000 这意味着 2013 年 8 月 1 日星期四 11:30:00 GMT+0530(印度标准时间),因此 UTC 时间不同,除了 5:30 时的缺陷外,还有 11:30 时的缺陷。

没有在服务器上使用以下代码,但我希望得到类似的结果 -

Calendar calendar = Calendar.getInstance();
String[] arr = dateStr.split("/");
calendar.set(new Integer(arr[2]), new Integer(arr[0]), new Integer(
        arr[1]));
return calendar.getTime();

请帮我解决这个问题。另外,在运行时进行比较时,我必须使用 new Date() 那应该怎么做呢?

【问题讨论】:

    标签: java datetime utc epoch java.util.date


    【解决方案1】:

    问题是您想同时在服务器和客户端上查看当前时间(以 UTC 毫秒为单位)吗?如果是这种情况,调用 System.currentTimeMillis() 应该返回相同的值(如果同时调用,则在美国和印度)。

    如果不是这样,也许您可​​能想将时区传递给 GregorianCalendar,如下所示:

    GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("US/Pacific"))
    

    如果问题仍然存在,也许您可​​以详细说明问题?

    【讨论】:

      【解决方案2】:

      java.util.Date 有很多问题,应该避免。相反,您应该使用 java.util.Calendar,并且可能使用特定的日历 java.util.GregorianCalendar。日历在一致性方面表现得更好,并且不依赖于操作系统的功能/细节。

      所以,开始使用Gregorian Calendars

      【讨论】:

      • 感谢会尝试使用公历。在日期时间转换方面没有太多经验。如果您能提供一些特定于该问题的代码,将会很有帮助。
      猜你喜欢
      • 2017-07-21
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多