我正在尝试日期时间戳格式,包括带冒号的时区。我做了几个实验来得到结果。这是我的发现。
Date date = new Date();
String zonedDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
SimpleDateFormat sdf = new SimpleDateFormat(zonedDateTimeFormat);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(new Date(date.getTime())));
如果我将时区设置为 UTC,我将得到这样的时间戳:
2020-11-03T21:14:07.449Z
但如果时区不是UTC
Date date = new Date();
String zonedDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
SimpleDateFormat sdf = new SimpleDateFormat(zonedDateTimeFormat);
System.out.println(sdf.format(new Date(date.getTime())));
时间戳将是这样的:2020-11-03T22:19:43.804+01:00
我想知道是否有可能在 UTC 时区内获取时间戳,例如:2020-11-03T21:14:07.449+00:00
而不是以大写 Z 结尾
?
您可以使用 Java 8 日期/时间 API,它深受 Joda Time 库的影响(显然也有 some overlap in developer effort ),但在某些方面有所不同。与 Joda Time 不同的是,Java 8 日期/时间 API 是 Java 自带的。
DateTimeFormatter类有这些模式字母:
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00
在您的情况下,小写的 x
应该会给出您想要的结果。
示例代码:
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.ZoneId;
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxx");
ZoneId zone = ZoneId.of("UTC");
ZonedDateTime d = ZonedDateTime.now(zone);
System.out.println(d.format(f));
输出:
2020-11-03T22:31:10.928+00:00
可能值得阅读 package description for the Java 8 Date and Time API了解 API 的一般原理,这与 java.util Date 和 Calendar 对象略有不同。
简而言之,主要思想是这个 API 中的所有日期和时间对象都是不可变的,如果你想修改或创建日期,你可以使用工厂方法创建其他日期和时间对象,如 of
或类似 with
的函数返回 datetime 对象的副本,但指定的字段已更改。
一些重要的类:
Instant
- a timestamp
LocalDate
- a date without a time, or any reference to an offset or time-zone
LocalTime
- a time without a date, or any reference to an offset or time-zone
LocalDateTime
- combines date and time, but still without any offset or time-zone
ZonedDateTime
- a "full" date-time with time-zone and resolved offset from UTC/Greenwich
ZoneId
- represents a time zone
要将 java.util.Date 对象转换为 Java 8 日期/时间 API 中的相应对象,请参阅:Convert java.util.Date to java.time.LocalDate