【问题标题】:set calendar object hour to 0将日历对象小时设置为 0
【发布时间】:2014-10-01 09:25:26
【问题描述】:

这是我的代码

    TimeZone timeZone = TimeZone.getTimeZone("UTC");
    Calendar calendar = Calendar.getInstance(timeZone);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0); 
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    Timestamp start = new Timestamp(calendar.getTime().getTime());

但时间戳结果例如 = 2014-09-30 02:00:00.0 我无法将小时数设置为 0。

任何建议。

【问题讨论】:

  • 那么结果"2014-09-30 02:00:00.0"是如何构造的?很可能是使用不同时区(不是 UTC)的格式化程序。
  • 设置小时为 22 和 DAY_OF_MONTH 为 DAY_OF_MONTH -1
  • 我建议您使用 joda-time 库来解决此类问题:joda.org/joda-time 这样您就可以通过调用 DateTime yourDateTime = DateTime.now().withSecondOfMinute(0 ).withMinuteOfHour(0).withHourOfDay(0);要检索您想要的日历对象,您可以在 joda time 日历中检查此方法:joda-time.sourceforge.net/api-release/org/joda/time/base/…

标签: java calendar timestamp


【解决方案1】:

调用Calendar.getTime() 后,您会得到一个Date 对象,它是一个没有时区信息的瞬间。

当您想要打印或呈现此实例时,如果未明确指定,格式化程序将使用默认时区,在您的情况下,这不是 UTC,而是 CET。

当您将此瞬间转换为String 时,您还必须说明您希望它呈现在哪个时区。您还必须在此处指定 UTC 时区。

例如如果使用SimpleDateFormat,你可以使用它的setTimeZone()方法。

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

System.out.println(sdf.format(start));

此外,如果您的结果来自您的数据库,您必须使用不带时区或带有 UTC 时区的 timestamp SQL 类型。

【讨论】:

    【解决方案2】:

    我来宾 icza 是对的。

    为了确定,试试这个:

    Timestamp start = new Timestamp(calendar.getTime().getTime());
    System.out.println(start.getTimezoneOffset());
    

    【讨论】:

      猜你喜欢
      • 2012-09-03
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多