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

huangapple go评论71阅读模式
英文:

How do you format current system datetime as UTC using String.format in Java?

问题

这段代码:

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()));

但是没有生效。

英文:

This code

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

gives a YYYYmmdd format using the current system time but the time zone is the current system default as well. How to make this code gives UTC date?

I tried

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

but not working.

答案1

得分: 3

使用 ZonedDateTime

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

Use ZonedDateTime:

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

答案2

得分: 2

由于您只需要显示年、月和日,最适合的类是 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 包中可用的日期时间类的概述

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

了解有关现代日期时间 API的更多信息,请参阅**教程:日期时间**。

英文:

Since you need to display just year, month and day, the most appropriate class for this would be LocalDate. Also, I suggest you use DateTimeFormatter which is not only specialized for formatting date, time, and time-zone information but also many other features like defaulting the parts of date-time to some values, localizing etc.

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));
	}
}

Output:

2020-09-11
20200911

Note that java.util.Date does not represent a Date/Time object. It simply represents the no. of milliseconds from the epoch of 1970-01-01T00:00:00Z. It does not have any time-zone or zone-offset information. When you print it, Java prints the string obtained by combining the date and time based on the time-zone of your JVM with the time-zone of your JVM. Date and time API from java.util is mostly deprecated and error-prone. I suggest you stop using java.util.Date and switch to java.time API.

The java.time API has a rich set of classes for different purposes e.g. if you need the information about the date and time, you can use LocalDateTime and if you need the information about the date, time, and time-zone, you can use ZonedDateTime or OffsetDateTime. The following table shows an overview of date-time classes available in java.time package:

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

Learn more about the modern date-time API from Trail: Date Time.

huangapple
  • 本文由 发表于 2020年9月11日 10:45:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63840137.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定