如果 Java Android 已经过了几分钟,如何检查此日期时间模式

Dea*_*lZg 2 java datetime android datetime-comparison

我从服务器收到此日期时间模式作为字符串。

萨。2023年1月7日 16:39:15

现在我想检查 1 分钟是否结束。就像当前时间和来自服务器的时间(作为字符串接收)之间的差距超过一分钟。

时区位于欧洲。比如奥地利。

Arv*_*ash 6

  1. 将给定的日期时间字符串解析为LocalDateTime.
  2. 通过应用 a将获得的值转换LocalDateTime为 a 。ZonedDateTimeZoneId
  3. ZonedDateTime获取应用中的电流ZoneId
  4. 最后,找到当前时间ZonedDateTimeZonedDateTime从日期时间字符串获取的时间之间的分钟数。

演示

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;

class Main {
    public static void main(String[] args) {
        String strDateTime = "Sa. 07.01.2023 16:39:15";

        DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE dd.MM.uuuu HH:mm:ss", Locale.GERMAN);

        // Note: change the ZoneId as per your requirement

        ZonedDateTime zdt = LocalDateTime.parse(strDateTime, parser)
                                         .atZone(ZoneId.of("Europe/Vienna"));
        System.out.println("Date-time received from the server: " + zdt);

        ZonedDateTime now = ZonedDateTime.now(zdt.getZone());
        System.out.println("Current date-time: " + now);

        System.out.println(ChronoUnit.MINUTES.between(zdt, now) > 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

示例运行的输出

Date-time received from the server: 2023-01-07T16:39:15+01:00[Europe/Vienna]
Current date-time: 2023-01-07T17:33:04.140599+01:00[Europe/Vienna]
true
Run Code Online (Sandbox Code Playgroud)

ONLINE DEMO

从Trail: Date Time中了解有关现代日期时间 API 的更多信息。


纳入Basil Bourque 建议的以下有价值的替代解决方案:

Instant如果最后切换到对象可能会更清楚。Instant从您的第一个中提取 an ZonedDateTime,然后更改 ZonedDateTime nowInstant now

class Main {
    public static void main(String[] args) {
        String strDateTime = "Sa. 07.01.2023 16:39:15";

        DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE dd.MM.uuuu HH:mm:ss", Locale.GERMAN);

        // Note: change the ZoneId as per your requirement

        Instant instantParsed = LocalDateTime.parse(strDateTime, parser)
                                             .atZone(ZoneId.of("Europe/Vienna"))
                                             .toInstant();
        System.out.println("Instant received from the server: " + instantParsed);

        Instant instantNow = Instant.now();
        System.out.println("Current instant: " + instantNow);

        System.out.println(ChronoUnit.MINUTES.between(instantParsed, instantNow) > 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

ONLINE DEMO