2

我正在尝试日期时间戳的格式,包括带冒号的时区。我做了几个实验来得到结果。这是我发现的。

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

4

1 回答 1

2

您可以使用 Java 8 日期/时间 API,它深受 Joda Time 库的影响(显然在开发人员的努力方面也有一些重叠),但在某些方面有所不同。与 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

可能值得阅读Java 8 日期和时间 API 的包描述,以了解 API 的一般理念,这与 java.util 日期和日历对象的理念有些不同。

简而言之,主要思想是此 API 中的所有日期和时间对象都是不可变的,如果您想修改或创建日期,您可以使用工厂方法of或类似with返回副本的函数创建其他日期和时间对象的日期时间对象,但指定的字段已更改。

一些重要的类:

  • Instant- 时间戳
  • LocalDate- 没有时间的日期,或对偏移量或时区的任何引用
  • LocalTime- 没有日期的时间,或对偏移量或时区的任何引用
  • LocalDateTime- 结合日期和时间,但仍然没有任何偏移或时区
  • ZonedDateTime- 带有时区的“完整”日期时间,并解决了与 UTC/格林威治的偏移量
  • ZoneId- 代表一个时区

要将 java.util.Date 对象转换为 Java 8 日期/时间 API 中的相应对象,请参阅:将 java.util.Date 转换为 java.time.LocalDate

于 2020-11-03T22:40:28.167 回答