如何使用Java中的String.format将当前系统日期时间格式化为UTC?

问题描述

代码

String.format("%1$tY%1$tm%1$td",new Date());

使用当前系统时间提供YYYYmmdd格式,但时区也是当前系统认值。如何使此代码给出UTC日期?

我尝试过

String.format("%1$tY%1$tm%1$td",Date.from(LocalDateTime.Now().atZone(ZoneId.of("UTC")).toInstant()));

但不起作用。

解决方法

使用ZonedDateTime

ZonedDateTime zonedDateTime = ZonedDateTime.now().withZoneSameInstant(ZoneId.of("UTC"));
System.out.println(String.format("%1$tY%1$tm%1$td",zonedDateTime));
,

由于只需要显示年,月和日,因此最合适的类别是LocalDate。另外,我建议您使用DateTimeFormatter,它不仅专门用于格式化日期,时间和时区信息,而且还具有许多其他功能,例如将日期时间部分默认为某些值,本地化等。

import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Today at UTC
        LocalDate date = LocalDate.now(ZoneOffset.UTC);

        // Define the formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuuMMdd");

        // Display LocalDate in its default format
        System.out.println(date);

        // Display LocalDate in the custom format
        System.out.println(date.format(formatter));
    }
}

输出:

2020-09-11
20200911

请注意,java.util.Date不代表日期/时间对象。它只是表示否。距1970-01-01T00:00:00Z的毫秒数。它没有任何时区或时区偏移信息。在打印时,Java会打印通过将基于JVM时区的日期和时间与JVM时区相结合而获得的字符串。 java.util中的日期和时间API大部分已被弃用且容易出错。建议您停止使用java.util.Date并切换到java.time API。

java.time API具有丰富的类集,可用于不同目的,例如如果需要有关日期和时间的信息,则可以使用LocalDateTime;如果需要有关日期,时间和时区的信息,则可以使用ZonedDateTimeOffsetDateTime 。下表显示了java.time软件包中的overview of date-time classes

enter image description here

the modern date-time API 了解有关Trail: Date Time的更多信息。