我有一个 Java (11) 应用程序,可以接收包含以下格式的日期/时间值的数据:
yyyy-mm-ddThh:mm:ss.sssZ
示例:2024-04-01T17:33:58.713Z
我需要能够将这些字符串解析为日期/时间对象,并能够使用和显示“本地”时间(例如美国中部时间)中的值。我认为这相当简单,但我一直在尝试很多我认为会起作用的事情,但事实并非如此。
使用上面的示例,我期望一个“本地”(假设美国中部)日期/时间代表:April 1, 2024 at 12:33:58.713 CDT
注意:我还没有想到如何处理“日光”与“标准”时间。也许
java.time
图书馆会处理这个问题?
我尝试过使用
LocalDateTime
和 ZonedDateTime
parse(...)
方法,以及指定或不指定“区域”的
DateTimeFormatter
。我无法得到任何东西来做我需要做的事情。
这是我尝试过的不同东西的课程:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeUtil {
private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
private static final DateTimeFormatter UTC = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.withZone(ZoneId.ofOffset("UTC", ZoneOffset.ofHours(0)));
private static final DateTimeFormatter LOCAL = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.withZone(ZoneId.ofOffset("UTC", ZoneOffset.ofHours(-6)));
public static LocalDateTime parse(Object object) {
if (object == null) {
return null;
}
return parse(object.toString());
}
public static LocalDateTime parse(String string) {
if (string == null || string.isBlank()) {
return null;
}
LocalDateTime dt = LocalDateTime.parse(string, FORMAT);
return dt;
}
public static ZonedDateTime parseUTC(String string) {
ZonedDateTime dt = ZonedDateTime.parse(string, UTC);
return dt;
}
public static ZonedDateTime parseLocal(String string) {
ZonedDateTime dt = ZonedDateTime.parse(string, LOCAL);
return dt;
}
}
我尝试的所有操作都只是返回一个日期/时间对象,其时间与源字符串的时间相同。尚未针对时区差异进行调整。有人可以告诉我我做错了什么或遗漏了什么吗?
你这样做,比原来复杂得多:
ZonedDateTime utc = ZonedDateTime.parse("2024-04-01T17:33:58.713Z");
ZonedDateTime inNewYork = utc.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println(utc);
System.out.println(inNewYork);
打印:
2024-04-01T17:33:58.713Z
2024-04-01T13:33:58.713-04:00[America/New_York]
我猜这就是你想要的。一些注意事项:
withZoneSameLocal
ZoneOffset.ofHours(-6)
EST 是一种你永远不应该使用的令人厌恶的东西。例如,您知道澳大利亚有“东部标准时间”这样的东西吗?现在是 UTC+10;它通常缩写为 AEST,但正如您所料,澳大利亚人通常不包含“A”。你也不称纽约时间为“USEST”,是吗?此外,这些 3 个字母的缩写词根本无法完成任务。还记得欧盟的决定吗?欧盟决定所有欧盟国家取消夏令时,但“不是”哪个国家取消夏令时。 CET 时区(中欧时间)非常大。像荷兰这样的地方可能想坚持夏令时。但像波兰这样的地方可能有冬天。几年后,“CET”将变得无用/模棱两可
Continent/BigCity
形式。不要使用其他的。