【问题标题】:Java DateFormat conversion automatically increases hour by 1Java DateFormat 转换自动将小时增加 1
【发布时间】:2015-12-14 16:46:09
【问题描述】:

我正在尝试以字符串形式获取日期及其输入格式字符串并将日期转换为输出格式。然而,在转换为 Date 之后,java 代码将小时数增加一。我无法理解导致该错误的原因。

我的代码:

try {
    DateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");

    DateFormat inputFormat = new SimpleDateFormat(format);

    Date date = inputFormat.parse(parameterValue);
    parameterValue = outputFormat.format(date);
    return parameterValue;
} catch (ParseException ex) {
    // take action
}

格式字符串:ddMMMyyyy / hh:mm z

输入日期:07DEC2015 / 10:02 GMT

输出日期:07/12/2015 11:02:00

【问题讨论】:

  • 您的系统时区是多少?哦,你几乎肯定想要HH 而不是hh
  • 在这篇文章中查看我的答案,它非常相似:stackoverflow.com/questions/34223125/…
  • 这可能是时区问题。假设您位于欧洲大陆,时区比格林威治标准时间早 1 小时,我是否正确?您可以尝试更改outputFormat 以在末尾添加z,您将获得它所显示的时区,这可能会更清楚地解释问题。
  • 我无法更改输出格式。但是我添加了这个“ outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));”到我的代码,它工作得很好。谢谢! hh 或 HH 是一样的。
  • @Anuja hhHH 有很大不同。我建议阅读文档。

标签: java parsing datetime date-format


【解决方案1】:

outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

解决了。

【讨论】:

    【解决方案2】:

    如果你不想使用时区,在 java 8 中你可以使用 LocalDate/LocalTime/LocalDateTime:

    LocalDateTime localDateTimeInstance = LocalDateTime.parse(dateToBeConverted, DateTimeFormatter.ofPattern(formatOfDateToBeConverted));
    return localDateTimeInstance.format("dd/MM/yyyy hh:mm:ss");
    
    
    /*
      Also check out ZoneDate, ZoneTime (for timezone)
      Checkout - LocalDate, LocalTime
    */
    

    【讨论】:

      猜你喜欢
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 2020-11-26
      相关资源
      最近更新 更多