从字符串创建 ZonedDateTime 的实例,时间与字符串相同 [Java]

Create an Instance of ZonedDateTime from String with same time as String [Java]

我想从 String 创建一个 ZonedDateTime 的实例。我想让“2021-03-18 8:00:00”变成“2021-03-18 8:00:00 EST”。我不希望意外变量通过将 8:00:00 转换为与显示时间不同的时间来进行干扰。即从 8:00:00 到 17:00:00.

我用来尝试转换它的代码是:

    SimpleDateFormat estForm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    estForm.setTimeZone(TimeZone.getTimeZone("EST"));
    String start = "2021-03-18 08:00:00";

    Date estDT = estForm.parse(start);

    final ZoneId zoneEST = ZoneId.of("US/Eastern");

    ZonedDateTime zoneEst = ZonedDateTime.ofInstant(estDT.toInstant(), zoneEST);

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    System.out.println(zoneEST);
    System.out.println(zoneEst);

这是我从中得到的最后一个输出:

US/Eastern
2021-03-18T09:00-04:00[US/Eastern]

嗯,你可以简单地做:

"2021-03-18 08:00:00" + " EST"

如果要将输入视为逻辑日期时间值,请解析为 LocalDateTime。这种类型是合适的,因为您的输入缺少时区指示符或与 UTC 的偏移量。

然后调用 atZone 将该日期和时间置于时区的上下文中。 EST 不是时区。这样的2-4个伪区只是代表了Daylight Saving Time (DST)是否生效的大概意思,甚至那也只是对一个区域的大概意思,并不精确。也不是标准化的,甚至不是唯一的。

我猜你想要纽约时间。

LocalDateTime
.parse( 
    "2021-03-18 08:00:00".replace( " " , "T" ) 
)                                                // Returns a `LocalDateTime` object.
.atZone(
    ZoneId.of( "America/New_York" ) 
)                                                // Returns a `ZonedDateTime` object.

通常最好让 DateTimeFormatter 在生成文本时通过 `ofLocalized… 方法自动本地化。但是如果你坚持你的特定方法,定义一个格式化模式。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss z" ) ;
String output = zdt.format( f ) ;

将代码放在一起。

        ZonedDateTime zdt = 
            LocalDateTime
            .parse( "2021-03-18 08:00:00".replace( " " , "T" ) )
            .atZone(
                ZoneId.of( "America/New_York" ) 
            )
        ;

        DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss z" ) ;
        String output = zdt.format( f ) ;

看到这个code run live at IdeOne.com

2021-03-18 08:00:00 EDT

正如我们在该输出中看到的那样,您想要的 EST 是不正确的,因为纽约时间在此日期时间之前几天将夏令时改为标准时间。