Dea*_*lZg 2 java datetime android datetime-comparison
我从服务器收到此日期时间模式作为字符串。
萨。2023年1月7日 16:39:15
现在我想检查 1 分钟是否结束。就像当前时间和来自服务器的时间(作为字符串接收)之间的差距超过一分钟。
时区位于欧洲。比如奥地利。
LocalDateTime.LocalDateTime为 a 。ZonedDateTimeZoneIdZonedDateTime获取应用中的电流ZoneId。ZonedDateTime与ZonedDateTime从日期时间字符串获取的时间之间的分钟数。演示:
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)
从Trail: Date Time中了解有关现代日期时间 API 的更多信息。
纳入Basil Bourque 建议的以下有价值的替代解决方案:
Instant如果最后切换到对象可能会更清楚。Instant从您的第一个中提取 anZonedDateTime,然后更改ZonedDateTime now为Instant 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)