首页 > 解决方案 > 如何在日期中找到小时,分钟的相等性

问题描述

我需要在 java 中找到小时、分钟的相等性(DST 中的 1 个日期,DST 之后的 1 个日期)。两个日期都是 UTC。DST 在英国 2020 年 10 月 26 日凌晨 2 点结束,因此在上面的示例中,小时和分钟是相等的。

  1. 日期 1 = 2020-10-22T07:00:00+0000
  2. 日期 2 = 2020-10-26T08:00:00+0000

标签: javadatetimetimetimezonetimezone-offset

解决方案


您的日期时间字符串具有 Zone-Offset ,+0000因此将它们解析为OffsetDateTime(使用适当的DateTimeFormatter)将是更自然的选择。将它们解析为OffsetDateTime后,将它们转换为ZonedDateTime与英国时区对应的值。作为最后一步,您需要获取ZonedDateTime.

import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // The given date-time strings
        String strDate1 = "2020-10-22T07:00:00+0000";
        String strDate2 = "2020-10-26T08:00:00+0000";

        // Define the formatter for the given date-time strings
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("u-M-d'T'H:m:sZ");

        // ZoneId of the UK
        ZoneId tzLondon = ZoneId.of("Europe/London");

        // Get the corresponding date-time in the UK
        ZonedDateTime zdt1 = OffsetDateTime.parse(strDate1, formatter).atZoneSameInstant(tzLondon);
        ZonedDateTime zdt2 = OffsetDateTime.parse(strDate2, formatter).atZoneSameInstant(tzLondon);

        System.out.println(zdt1);
        System.out.println(zdt2);

        // Get local date from ZonedDateTime
        LocalTime lt1 = zdt1.toLocalTime();
        LocalTime lt2 = zdt2.toLocalTime();

        System.out.println(lt1);
        System.out.println(lt2);
    }
}

输出:

2020-10-22T08:00+01:00[Europe/London]
2020-10-26T08:00Z[Europe/London]
08:00
08:00

推荐阅读