【问题标题】:Check if Date is the next day after 00:00 am检查日期是否是次日上午 00:00 之后
【发布时间】:2021-02-27 13:46:52
【问题描述】:

如果每天重新执行应用程序中的某个操作,我的连胜计数器会增加。我想在打开应用程序时检查它,最简单的方法是什么?

我知道我可以签入 CalendarDate 对象,如果是昨天+1,就像这里
Check if a date is "tomorrow" or "the day after tomorrow"

但这还没有考虑到时间,对吧?因为如果操作是在24.02. 7AM 上完成的,那么它必须是25.02. 7AM+(24 小时)才能工作?

【问题讨论】:

  • 这不是很清楚,抱歉。如果最后一次操作是在 2 月 24 日 07:00 执行的,您是说只有在 2 月 25 日 07:00 到 24:00 之间执行操作时才应该增加计数器?或者,它将被重置的上限是多少?
  • 用户可以通过更改设备的时区来作弊吗?
  • @OleV.V.不,早上 7 点只是一个例子。不,如果用户在 24 日 00:00 到 25 日 00:00 之间没有采取任何行动,我希望它被重置。这是用户每天必须执行 1 次的“日常任务”的计数器,如果他跳过一天,计数器会重置。
  • @OleV.V.是的,我想过,如果用户作弊怎么办?我不认为我可以防止作弊。

标签: android date datetime


【解决方案1】:

我知道我可以只签入日历或日期对象,如果它是 昨天+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 的更多信息。

【讨论】:

  • 嗯,谢谢你的信息。但是您不认为这是一个非常复杂的解决方案吗?我只想检查一个布尔值,看看用户是否在 24 小时内执行了操作。
  • @Big_Chair - 既然您已经了解了现代日期时间 API,我建议您学习和练习 Trail: Date Time。现代日期时间 API 非常丰富,因此您应该能够在使用它之后解决任何特定问题。如果您在某些时候遇到困难,请随时发布问题/cmets。祝你成功!
猜你喜欢
  • 1970-01-01
  • 2015-07-19
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
  • 2015-02-03
  • 1970-01-01
  • 1970-01-01
  • 2012-07-28
相关资源
最近更新 更多