如何在日期中找到小时、分钟的相等性

How to find equality of hr, min in date

我需要在 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
ZoneId zoneUk = ZoneId.of("Europe/London");

ZonedDateTime a = ZonedDateTime.parse("2020-10-22T07:00:00+00:00").withZoneSameInstant(zoneUk);
ZonedDateTime b = ZonedDateTime.parse("2020-10-26T08:00:00+00:00").withZoneSameInstant(zoneUk);

注意时间偏移中额外的:,否则无法解析。

System.out.println(a); // 2020-10-22T08:00+01:00[Europe/London]
System.out.println(b); // 2020-10-26T08:00Z[Europe/London]
  
System.out.println(a.toLocalTime()); // 08:00
System.out.println(b.toLocalTime()); // 08:00
  
System.out.println(a.toLocalTime().equals(b.toLocalTime())); // true

您的 date-time 字符串有 Zone-Offset 个 +0000,因此将它们解析为 OffsetDateTime(使用适当的 DateTimeFormatter)将是更自然的选择.将它们解析为 OffsetDateTime 后,将它们转换为对应于英国 time-zone 的 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