java - 如何检查时间段与Java中的另一个时间段重叠 [英] How to check a timeperiod is overlapping another time period in java

查看:32
本文介绍了java - 如何检查时间段与Java中的另一个时间段重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查一个时间段是否与同一天的另一个时间段重叠.

How to check a time period is overlapping another time period in the same day.

例如

  1. 上午 7:00 至上午 10:30 与上午 10:00 至上午 11:30 重叠
  2. 上午 7:00 至上午 10:30 与上午 8:00 至上午 9:00 重叠
  3. 上午 7:00 至上午 10:30 与上午 5:00 至上午 8:00 重叠

推荐答案

有一个简单的解决方案,这里表示为一个实用方法:

There is a simple solution, expressed here as a utility method:

public static boolean isOverlapping(Date start1, Date end1, Date start2, Date end2) {
    return start1.before(end2) && start2.before(end1);
}

此代码要求两个周期之间至少共享一毫秒才能返回true.

This code requires there to be at least one millisecond to be shared between the two periods to return true.

如果认为相邻的时间段重叠"(例如 10:00-10:30 和 10:30-11:00),则需要稍微调整逻辑:

If abutting time periods are considered to "overlap" (eg 10:00-10:30 and 10:30-11:00) the logic needs to be tweaked ever so slightly:

public static boolean isOverlapping(Date start1, Date end1, Date start2, Date end2) {
    return !start1.after(end2) && !start2.after(end1);
}

这种逻辑更常出现在数据库查询中,但同样的方法适用于任何上下文.

This logic more often comes up in database queries, but the same approach applies in any context.

一旦你意识到它有多简单,你首先会踢自己,然后把它存入银行!

Once you realise just how simple it is, you at first kick yourself, then you put it in the bank!

这篇关于java - 如何检查时间段与Java中的另一个时间段重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆