有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

日期仅重置时间,并在java中将其转换为utc

我看到很多帖子,他们正在设置使用Instance的日期和时间。现在()。但是我的要求有点不同

我有UTC时间,比如-2020-05-12T12:48:00我只想将时间设置为“00:30:00”(上午12:30),我的时区是Ameria/纽约

我的问题是,我怎样才能将时间设置为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


共 (1) 个答案

  1. # 1 楼答案

    编辑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