Java中的CDT到EST时间转换未格式化
我试图将我的时间戳从 CST 更改为 EST,但奇怪的是它不起作用,我很清楚为什么。
String timestamp = "Wed Jul 07 10:35:10 CDT 2021";
String formattedTimestamp;
SimpleDateFormat sdfGFTime = new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy", Locale.US);
TimeZone obj = TimeZone.getTimeZone("America/New_York");
Date date = null;
sdfGFTime.setTimeZone(obj);
date = sdfGFTime.parse(timestamp);
formattedTimestamp = sdfGFTime.format(date);
System.out.println(formattedTimestamp);
输出:
Wed Jul 07 10:35:10 CDT 2021
预期的:
Wed Jul 07 11:35:10 EST 2021
关于我可能会做什么不正确的任何想法?
回答
时间
我建议您使用 java.time,现代 Java 日期和时间 API 来处理您的日期和时间工作。让我们首先定义您的格式化程序:
private static final DateTimeFormatter DTF
= DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
现在,转换是这样的:
String timestamp = "Wed Jul 07 10:35:10 CDT 2021";
ZonedDateTime parsed = ZonedDateTime.parse(timestamp, DTF);
ZonedDateTime converted
= parsed.withZoneSameInstant(ZoneId.of("America/New_York"));
String formattedTimestamp = converted.format(DTF);
System.out.println(formattedTimestamp);
输出与您所说的不完全相同,但关闭:
2021 年 7 月 7 日星期三 11:35:10 EDT
此外,在纽约,他们使用夏令时(夏令时),因此东部时间的时区缩写在一年中的这个时候被指定为 EDT,而不是 EST。
你的代码出了什么问题?
这个有点棘手,但只是无数SimpleDateFormat不按我们最初期望的方式行事的例子中的一个。解析字符串时,SimpleDateFormat会将其时区设置为从字符串解析的时区。您刚刚在此之前设置了时区,您的设置只是默认丢失。所以你得到Date格式化回它来自的同一时区。这就是为什么我建议您永远不要使用SimpleDateFormat.
教程链接
Oracle 教程:解释如何使用 java.time 的日期时间。