java9-代码:
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class TimeChecker {
/**
* 判断更新时间是否距离当前时间超过1小时(向前或向后)
* @param updatedAt 待校验的时间(不可为null)
* @return true:超过1小时;false:1小时内或相等
* @throws NullPointerException 当updatedAt为null时抛出
*/
public static boolean isMoreThanOneHourAway(LocalDateTime updatedAt) {
if (updatedAt == null) {
throw new NullPointerException("更新时间不可为null");
}
LocalDateTime now = LocalDateTime.now();
// 计算双向时间差(处理未来时间场景)
long secondsDiff = Math.abs(Duration.between(updatedAt, now).getSeconds());
return secondsDiff > ChronoUnit.HOURS.toSeconds(1);
}
// 测试用例
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
// 场景1:1小时前(精确1小时)
LocalDateTime oneHourAgo = now.minusHours(1);
System.out.println("1小时前:" + isMoreThanOneHourAway(oneHourAgo)); // 输出:false
// 场景2:1小时1秒前(超过1小时)
LocalDateTime overOneHour = now.minusHours(1).minusSeconds(1);
System.out.println("1小时1秒前:" + isMoreThanOneHourAway(overOneHour)); // 输出:true
// 场景3:未来1小时(精确1小时)
LocalDateTime oneHourLater = now.plusHours(1);
System.out.println("未来1小时:" + isMoreThanOneHourAway(oneHourLater)); // 输出:false
// 场景4:未来1小时1秒(超过1小时)
LocalDateTime futureOver = now.plusHours(1).plusSeconds(1);
System.out.println("未来1小时1秒:" + isMoreThanOneHourAway(futureOver)); // 输出:true
// 场景5:当前时间(相等)
System.out.println("当前时间:" + isMoreThanOneHourAway(now)); // 输出:false
}
}
java8-代码:
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class TimeChecker {
/**
* 判断更新时间是否距离当前时间超过1小时(Java 8兼容版)
* @param updatedAt 待校验的时间(不可为null)
* @return true:超过1小时;false:1小时内或相等
* @throws NullPointerException 当updatedAt为null时抛出
*/
public static boolean isMoreThanOneHourAway(LocalDateTime updatedAt) {
if (updatedAt == null) {
throw new NullPointerException("更新时间不可为null");
}
LocalDateTime now = LocalDateTime.now();
// Java 8兼容方案:使用ChronoUnit.HOURS.getDuration()获取1小时的Duration
Duration oneHour = ChronoUnit.HOURS.getDuration(); // 等价于Duration.ofHours(1)
Duration diff = Duration.between(updatedAt, now);
// 处理双向时间差(包含未来时间场景)
return Math.abs(diff.getSeconds()) > oneHour.getSeconds();
}
// 测试用例(与Java 8行为一致)
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
// 场景1:1小时前(精确1小时,Java 8返回false)
LocalDateTime oneHourAgo = now.minusHours(1);
System.out.println("1小时前:" + isMoreThanOneHourAway(oneHourAgo)); // 输出:false
// 场景2:1小时1秒前(超过1小时)
LocalDateTime overOneHour = now.minusHours(1).minusSeconds(1);
System.out.println("1小时1秒前:" + isMoreThanOneHourAway(overOneHour)); // 输出:true
}
}