Java中验证一个时间是否在时间段之内

本文介绍了一种方法,用于判断当前时间是否处于特定的时间段内。通过将当前时间与预设的开始和结束时间进行比较,实现了精确的时间区间判断。

例子:验证当前时间是否在08:00--18:00这个时间段内

思路:利用Date类型的 after、before方法实现,截取当前时间的HH:mm 字符串数据,然后采用一样的方法转化为date类型进行比较,这样比较的准确度比较高

代码:

/**
	 * 判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致
	 *
	 * @param now 当前时间
	 * @param startTime 开始时间段
	 * @param endTime 结束时间段
	 * @return
	 * @author jqlin
	 */
	public static boolean isEffectiveDate(Date now, String startTime, String endTime) throws ParseException {
		String format = "HH:mm";
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String nowtTime = sdf.format(now);
		Date nowDate = sdf.parse(nowtTime);
		Date startDate = sdf.parse(startTime);
		Date endDate = sdf.parse(endTime);

		if (nowDate.getTime() == startDate.getTime()
				|| nowDate.getTime() == endDate.getTime()) {
			return true;
		}

		Calendar date = Calendar.getInstance();
		date.setTime(nowDate);

		Calendar begin = Calendar.getInstance();
		begin.setTime(startDate);

		Calendar end = Calendar.getInstance();
		end.setTime(endDate);

		if (date.after(begin) && date.before(end)) {
			return true;
		} else {
			return false;
		}
	}

    

### Java 实现检查时间段是否在另一个时间段内的方法 为了实现这一功能,可以创建一个 `TimeInterval` 类来表示时间段,并定义相应的方法来进行比较。下面是一个具体的实现方式: #### 定义 TimeInterval 类 首先,定义一个用于存储起始时间和结束时间的对象。 ```java import java.time.LocalDateTime; public class TimeInterval { private LocalDateTime start; private LocalDateTime end; public TimeInterval(LocalDateTime start, LocalDateTime end) { this.start = start; this.end = end; } public boolean contains(TimeInterval other) { return !this.start.isAfter(other.getEnd()) && !this.end.isBefore(other.getStart()); } public LocalDateTime getStart() { return start; } public void setStart(LocalDateTime start) { this.start = start; } public LocalDateTime getEnd() { return end; } public void setEnd(LocalDateTime end) { this.end = end; } } ``` 此代码片段展示了如何通过 `contains()` 方法判断给定的时间区间 `other` 是否完全被当前实例所覆盖[^1]。 #### 使用示例 接下来展示一段简单的测试程序,用来验证上述逻辑的有效性。 ```java import java.time.LocalDateTime; public class Main { public static void main(String[] args) { // 创建两个不同的时间间隔对象 TimeInterval intervalA = new TimeInterval( LocalDateTime.of(2023, 9, 1, 8, 0), LocalDateTime.of(2023, 9, 1, 17, 0)); TimeInterval intervalB = new TimeInterval( LocalDateTime.of(2023, 9, 1, 9, 0), LocalDateTime.of(2023, 9, 1, 16, 0)); System.out.println("intervalB is within intervalA? " + intervalA.contains(intervalB)); } } ``` 这段代码会输出 `true` 表明 `intervalB` 的确是在 `intervalA` 范围之内[^2]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值