Java XMLGregorianCalendar 正在改变时间 - 奇怪的行为

时间:2021-06-02 06:34:07

标签: java xmlgregoriancalendar

我有一个日期作为输入 = 2021-03-12T10:42:01.000Z....我想转换成这种格式:

String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";


public String getDate(XMLGregorianCalendar input) {
    DateFormat f = new SimpleDateFormat(pattern);
    input.toGregorianCalendar().setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
    String output = f.format(input.toGregorianCalendar().getTime());
    System.out.println(output);
}

2021-03-12T12:42:01+0200

基本上,它增加了 2 小时。可能跟时区有关,我没在别的电脑上测试过。我有两个问题:

  • 为什么会这样
  • 我该怎么做才能避免它?这是一个遗留应用程序,所以我不想做大的改变

谢谢

2 个答案:

答案 0 :(得分:3)

<块引用>

基本上,它增加了 2 小时

不是真的。它为您提供同一时刻的输出,但在您的系统本地时区中 - 因为您正在创建一个 SimpleDateFormat 而不指定时区(或文化):

DateFormat f = new SimpleDateFormat(pattern);

我个人建议完全避免使用 java.text.SimpleDateFormat,而更喜欢 java.time 类型和格式化程序。但是,如果您确实想使用 SimpleDateFormat,只需确保将时区设置为 UTC(假设您总是想要 UTC)并理想地设置文化(例如设置为 Locale.ROOT)。

答案 1 :(得分:3)

Answer by Jon Skeet 是正确的,而且很聪明。您似乎只是看到了时区调整。您的两个字符串 2021-03-12T10:42:01.000Z2021-03-12T12:42:01+0200 代表同一时刻。中午 12 点(如果比 UTC 早两个小时)与上午 10 点相同,但与 UTC 的偏移量为零时分秒。

而且,正如在另一个答案中提到的,您真的应该避免使用与最早版本的 Java 捆绑在一起的糟糕的日期时间类。

tl;博士

myXMLGregorianCalendar     // Legacy class, representing a moment as seen in some time zone.
.toGregorianCalendar()     // Another legacy class, also representing a moment as seen in some time zone.
.toZonedDateTime()         // A modern *java.time* class, representing a moment as seen in some time zone.
.toInstant()               // Another *java.time* class, for representing a moment as seen in UTC.
.truncatedTo(              // Lopping off some smaller part of the date-time value.
    ChronoUnit.SECONDS     // Specifying whole seconds as our granularity of truncation, so lopping off any fractional second.
)                          // Returns another `Instant` object, rather than altering (mutating) the original, per immutable objects pattern.
.toString()                // Generating text representing the content of our `Instant` object, using standard ISO 8601 format.

java.time

现代方法使用 java.time 类,多年前取代了 SimpleDateFormatXMLGregorianCalendar GregorianCalendar 等。

转换传统<——>现代

您可以轻松地从遗留类型转换为 java.time。在旧类上寻找新的 to/from 方法。

ZonedDateTime zdt = myXMLGregorianCalendar.toGregorianCalendar().toZonedDateTime() ;

调整到零偏移

通过提取 Instant 将任何时区调整为 UTC。此类代表以 UTC 格式显示的时刻,始终以 UTC 格式显示。

Instant instant = zdt.toInstant() ; 

了解 zdtinstant 都代表同一时刻,时间线上的同一点,但它们的挂钟时间不同。

截断

鉴于您的问题中看到的格式模式,您似乎希望以整秒的粒度工作。要删除任何小数秒,请截断为秒。

Instant truncated = instant.truncatedTo( ChronoUnit.SECONDS ) ;

ISO 8601

您想要的文本格式在 ISO 8601 标准中定义。该标准在 java.time 中默认用于解析/生成字符串。所以不需要指定任何格式模式。

String output = truncated.toString() ;
相关问题