【问题标题】:How to get the same output of departed Date.parse() in groovy?如何在 groovy 中获得与离开的 Date.parse() 相同的输出?
【发布时间】:2022-11-10 19:20:59
【问题描述】:

我有一个运行旧版本的 spring 应用程序的应用程序。该应用程序具有使用 Date.parse 创建日期对象的功能,如下所示

Date getCstTimeZoneDateNow() {
  String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
  def zonedDateString = new Date().format(dateFormat, TimeZone.getTimeZone('CST'))
  Date date = Date.parse(dateFormat, zonedDateString)
  return date // Tue Oct 18 20:36:12 EDT 2022 (in Date)
}

但是,不推荐使用上面的代码。我需要产生相同的结果。 我阅读了其他帖子,似乎首选CalenderSimpleDateFormatter。 而且我认为SimpleDateFormatter 具有更多功能。

这篇文章帮助我更多地了解以下代码中发生的事情 SimpleDateFormat parse loses timezone

Date getCstTimeZoneDateNow() {
  Date now = new Date()
  String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

  SimpleDateFormat sdf = new SimpleDateFormat()
  sdf.setTimeZone(TimeZone.getTimeZone('CST'))

  // cstDateTime prints times in cst
  String cstDateTime = sdf.format(now)  // 2022-10-18T20:36:12.088Z (in String)
  // JVM current time
  Date date = sdf.parse(cstDateTime) // Tue Oct 18 21:36:12 EDT 2022 (in Date)

  return date 
}

在这里,我的目标是返回格式为 Tue Oct 18 20:36:12 EDT 2022 的日期对象 格式很好。但是,正如帖子所说,当我执行sdf.parse() 时,它会在 JVM 时间打印。 这意味着,格式很好,但时区已关闭。 我怎样才能得到与以前完全相同的结果? 它不必使用SimpleDateFormatter。可以是任何东西。

非常感谢您的阅读和您的时间。

【问题讨论】:

  • 您使用的是 Java 8+ 吗?
  • 是的,它是 Java 8
  • 似乎CalenderSimpleDateFormatter 是首选不,恰恰相反!这些类设计不佳且早已过时,后者尤其是出了名的麻烦。在 Java 或 JVM 中,您绝对应该使用 java.time, the modern Java date and time API

标签: spring-boot date groovy timezone simpledateformat


【解决方案1】:

也许重要的是,日期始终与时区无关。给定的示例显示了 Java 规范的预期工作:

def format = new SimpleDateFormat()
format.setTimeZone(TimeZone.getTimeZone("CST"))
println new Date()
def date = format.parse(format.format(new Date()))
printf "parsed to %s%n", date
printf "formatted to %s (%s)%n", format.format(date), format.getTimeZone().getDisplayName()

在输出中,请注意,当使用 Format 和 toString() 时,会相应地显示不同的时间,这非常好,因为首先我们格式化然后以相同的格式再次解析,因此是相同的时区。稍后,我们使用 Date.toString() 输出日期,这次使用系统默认时区,在调用 Date.toString() 时始终使用该时区。在输出中,反映了时区偏移:

Thu Oct 20 09:22:58 EDT 2022
parsed to Thu Oct 20 09:22:00 EDT 2022
formatted to 10/20/22 8:22 AM (Central Standard Time)

【讨论】:

  • 对不起,你是对的。我没有复制和粘贴,所以我有一个错字。时区设置正确。这就是我在我的应用程序中拥有的
  • 我想即使我更新了模式,我的问题也不会得到解决,对吗?
  • 我仍然无法重现任何问题,因此如果仍然给出意外结果,可能值得再试一次并打印出更多信息。
  • 是的,我现在试过了。它显示我是 11:07。我想要的是 10:07 格式是正确的。时区已关闭
  • 嗨,请提供您使用的确切代码(即完整的单个可执行类文件)以及生成的完整输出,否则它只是在猜测您可能做错了什么。事实上,java.util.Date 对时区一无所知。谢谢。
猜你喜欢
  • 2016-06-19
  • 2014-12-28
  • 1970-01-01
  • 1970-01-01
  • 2021-08-01
  • 1970-01-01
  • 2014-12-04
  • 2021-02-03
  • 2020-09-24
相关资源
最近更新 更多