【问题标题】:Android - Determining whether LocalTime is between a set of time (including past midnight and after midnight)Android - 确定 LocalTime 是否在一组时间之间(包括午夜过后和午夜之后)
【发布时间】:2021-09-04 16:12:01
【问题描述】:

目前我正在尝试找出某个时间是否介于 startTime-1 Hour 和 endTime 之间。

目前我的代码是:

if (localTimeNow.isAfter(startShift.minus(1, ChronoUnit.HOURS)) &&
        localTimeNow.isBefore(endShift)) {
    Toast.makeText(this, "In shift", Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(this, "Not in shift", Toast.LENGTH_SHORT).show();
}

如果假设startShift 位于 08:00 和 endShift 位于 16:00,这将很有效,但是当我将 startShift 放在 22:00 和 endShift 在06:00。

对这里的逻辑有什么建议吗?

【问题讨论】:

  • 你查了吗this
  • 啊,我其实也有类似这样的方法,但不是那么干净!谢谢!他们的解决方案也很不错,猜你应该把这个作为答案发布,引用他们的答案,以防有人在查询时遇到我的问题

标签: android java-time


【解决方案1】:

按照建议将此作为答案发布。这是午夜问题的解决方案,即使间隔跨越午夜,它也能按预期工作。

/**
 * Takes into consideration that the interval may span accross midnight
 *
 * @param clock to make unit testing easier, just replace for Clock.systemUTC() in your code 
 * @param start the interval start
 * @param end the interval end
 * @return true if "now" is inside the specified interval
 */
static boolean isNowBetweenLocalTime(Clock clock, final LocalTime start, final LocalTime end) {
    LocalTime now = LocalTime.now(clock);

    // if interval crosses midnight
    if (end.isBefore(start)) {
        if (now.isAfter(start) && now.isAfter(end)) {
            return true;
        }
        if (now.isBefore(start) && now.isBefore(end)) {
            return true;
        }
        return false;
    }

    // if interval does not cross midnight
    if (end.isAfter(start)) {
        if (now.isAfter(start) && now.isBefore(end)) {
            return true;
        }
        return false;
    }

    return false; // interval is 0 so start and end always outside interval
}

原帖 - https://stackoverflow.com/a/64935458/4694013

【讨论】:

    猜你喜欢
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2013-11-07
    相关资源
    最近更新 更多