已经指出了根本原因,并在accepted answer 中提出了解决方案。这个答案是为了向未来的访问者介绍现代的 Date-Time API。
java.time
java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern Date-Time API*。
使用现代日期时间 API java.time 的解决方案:
import java.time.Instant;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.now();
System.out.println(instant);
}
}
样本运行的输出:
2021-07-03T14:08:02.594203Z
ONLINE DEMO
Instant 表示UTC 中时间轴上的一个瞬时点。输出中的Z 是零时区偏移的timezone designator。它代表 Zulu 并指定 Etc/UTC 时区(时区偏移量为 +00:00 小时)。
注意:如果你有java.util.Date的对象,你可以将其转换为Instant,如下所示:
Date date = new Date(); // A sample date
Instant instant = date.toInstant();
如何在特定时区显示当前日期时间:
使用ZonedDateTime#now 或ZonedDateTime#now(ZoneId) 显示特定时区的当前日期时间。
演示:
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// The current date-time in the JVM's timezone
ZonedDateTime zdtDefaultTz = ZonedDateTime.now();
System.out.println(zdtDefaultTz);
// The current date-time in a specific timezone
ZonedDateTime zdtNewYork = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println(zdtNewYork);
}
}
样本运行的输出:
2021-07-03T15:19:48.007549+01:00[Europe/London]
2021-07-03T10:19:48.010048-04:00[America/New_York]
ONLINE DEMO
如果您有java.util.Date 或Instant 的实例,如何在特定时区显示当前日期时间:
将Instant 转换为ZonedDateTime,表示所需时区中的日期时间,例如
ZonedDateTime zdt = instant.atZone(ZoneId.of("America/New_York"));
演示:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.now(); // new Date().toInstant()
ZonedDateTime zdtDefaultTz = instant.atZone(ZoneId.systemDefault());
System.out.println(zdtDefaultTz);
ZonedDateTime zdtNewYork = instant.atZone(ZoneId.of("America/New_York"));
System.out.println(zdtNewYork);
ZonedDateTime zdtUtc = instant.atZone(ZoneId.of("Etc/UTC"));
System.out.println(zdtUtc);
}
}
输出:
2021-07-03T15:24:23.716050+01:00[Europe/London]
2021-07-03T10:24:23.716050-04:00[America/New_York]
2021-07-03T14:24:23.716050Z[Etc/UTC]
ONLINE DEMO
通过 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。