仅重置时间并将其转换为 java 中的 utc

Reset only the time and convert it to utc in java

我看到很多 post 他们正在设置 instace.now() 的日期和时间。但是我的要求有点不同。

我的 UTC 时间如 - 2020-05-12T12:48:00 我只想将时间设置为“00:30:00”(12:30 AM) 我的时区是 Ameria/NewYork?

我的问题是如何将时间设置为 00:30:00(上午 12:30)?当我将其转换为 UTC 时,我需要得到以下结果

input: 2020-05-12T6:30:00

output : Without day light saving : 2020-05-12T4:30:00 With daylight saving : 2020-05-12T5:30:00

编辑 2:

I assume today's 12:30 AM is equal to UTC 04:30:00.

你是对的。为了获得该结果,我们需要在将时间强制为 12:30 上午后,将 从纽约时间转换为 UTC。与我之前的答案相比,这是相反的转换。

    ZoneId zone = ZoneId.of("America/New_York");
    LocalTime wantedNyTime = LocalTime.of(0, 30); // 12:30 AM

    String utcDateTimeString = "2020-05-12T06:30:00";
    OffsetDateTime newUtcTime = LocalDateTime.parse(utcDateTimeString)
            .atOffset(ZoneOffset.UTC)               // Interpret in UTC
            .atZoneSameInstant(zone)                // Convert to time zone
            .with(wantedNyTime)                     // set time to 00:30
            .toOffsetDateTime()
            .withOffsetSameInstant(ZoneOffset.UTC); // Convert back to UTC

    System.out.println(newUtcTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

输出为:

2020-05-12T04:30:00

今天和昨天夏令时 (DST) 在纽约生效(自 3 月 8 日起)。要查看一年中的标准时间部分会发生什么:

    String utcDateTimeString = "2020-02-29T03:12:00";

2020-02-28T05:30:00

原回答

    ZoneId zone = ZoneId.of("America/New_York");
    LocalTime wantedUtcTime = LocalTime.of(9, 30); // 09:30

    String utcDateTimeString = "2020-05-12T12:48:00";
    ZonedDateTime newUtcTime = 
        LocalDateTime                   // Represents a date and time-of-day, but lacks the context of a time zone or offset.
            .parse(utcDateTimeString)   // Returns a `LocalDateTime` object.
            .atOffset(ZoneOffset.UTC)   // Returns a `OffsetDateTime`. 
            .with(wantedUtcTime)        // Returns another `OffsetDateTime`, per immutable objects.
            .atZoneSameInstant(zone);   // Returns a `ZonedDateTime` object.

    System.out.println(newUtcTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

输出:

2020-05-12T05:30:00

编辑:

My time zone is - America/New_York

代码的作用:它解析字符串并以 UTC 格式解释它,因为您说它是 UTC 格式的。它将时间设置为 09:30(在本例中早了 3 个多小时),因为这将为我们提供您想要的一天中的最后时间。最后,它转换为所选时区,减去 4 小时得到您想要的夏令时 05:30。

以下是一年中标准时间部分的日期:

    String utcDateTimeString = "2020-02-29T03:12:00";

2020-02-29T04:30:00