我有一个连续计数器,如果应用程序中的操作每天重新执行,则该计数器会增加。我想在打开应用程序时检查它,最简单的方法是什么?
我知道我可以只签入 Calendar
或 Date
对象,如果是昨天+1,就像这里
Check if a date is "tomorrow" or "the day after tomorrow"
但那不是考虑时间,对吧?因为如果操作是在 24.02. 7AM
上完成的,那么它必须是 25.02. 7AM+
(24 小时)才能起作用?
答案 0 :(得分:3)
我知道我可以只签入一个日历或日期对象,如果它是 昨天+1 ...
java.util
日期时间 API 及其格式化 API SimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到 modern date-time API。
但那不是考虑时间,对吧?因为如果动作是 24.02 完成。早上 7 点,那么它必须是 25.02。早上 7 点+(24 小时) 它工作吗?
java.time API(现代日期时间 API)为您提供 LocalDateTime
来处理本地日期和时间(即一个地点的日期和时间,而不需要将其与另一个地方的日期和时间进行比较,因此不处理时区)。但是,当要将其与另一个地点的日期和时间进行比较时,而不是在同一时区,您需要 ZonedDateTime
(根据 DST 自动调整日期和时间对象)或 OffsetDateTime
(处理`固定时区偏移)等。下面给出了java.time类型的概述:
演示:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Main {
public static void main(String args[]) {
LocalDate date = LocalDate.of(2020, 2, 23);
LocalTime time = LocalTime.of(7, 0);
LocalDateTime ldt = LocalDateTime.of(date, time);
System.out.println(ldt);
LocalDateTime afterTenHoursTwentyMinutes = ldt.plusHours(10).plusMinutes(20);
LocalDateTime tomorrow = ldt.plusDays(1);
LocalDateTime theDayAfterTomorrow = ldt.plusDays(2);
System.out.println(afterTenHoursTwentyMinutes);
System.out.println(tomorrow);
System.out.println(theDayAfterTomorrow);
if (!afterTenHoursTwentyMinutes.isAfter(theDayAfterTomorrow)) {
System.out.println("After 10 hours and 20 minutes, the date & time will not go past " + tomorrow);
} else {
System.out.println("After 10 hours and 20 minutes, the date & time will go past " + tomorrow);
}
}
}
输出:
2020-02-23T07:00
2020-02-23T17:20
2020-02-24T07:00
2020-02-25T07:00
After 10 hours and 20 minutes, the date & time will not go past 2020-02-24T07:00
从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。