java中cdt到est时间的转换未格式化

t30tvxxf  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(430)

我正试图将我的时间戳从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

我现在能做什么有什么想法吗?

dphi5xsq

dphi5xsq1#

java.time

我建议您在日期和时间工作中使用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,而不是est。

你的代码出了什么问题?

这是一个有点棘手的好吧,但只是一个无尽的例子之一 SimpleDateFormat 没有表现出我们最初期望的样子。当您解析字符串时 SimpleDateFormat 将其时区设置为从字符串解析的时区。在那之前你已经设置了时区,而你的设置只是默认丢失了。所以你得到了 Date 格式化回它来自的同一时区。这就是为什么我建议你永远不要使用 SimpleDateFormat .

教程链接

oracle教程:说明如何使用java.time的日期时间。

相关问题