老规矩话不多说直接上代码:
老办法: 我们通常使用这种办法来比较两个时间的大小
public static void main(String[] args) throws ParseException {
//规定时间格式
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//指定一个时间,这里时间可以自己定,也可以从数据库取
Date futureTime= format.parse("2022-04-26 23:59:59");
//Date futureTime= format.parse("2011-05-12 15:16:00");
//现在时间
Date nowTime= new Date();
//比较两个时间,如果返回1说明futureTime>nowTime-1说明小于 0说明等于
int sign=futureTime.compareTo(nowTime);
if(sign>0){
System.out.println("在有效期");
}else{
System.out.println("已过期");
}
}
Java8 新特性:在Java8后我们可以使用LocalDateTime和Duration类更方便的操作时间
//开始时间
LocalDateTime start = LocalDateTime.of(2023,1,1,8,0,0);
//结束时间
LocalDateTime end = LocalDateTime.of(2023,1,2,8,30,30);
//计算时间差
Duration between = Duration.between(start, end);
//间隔天数
long day = between.toDays();
System.out.println("相差:"+day+"天");
//间隔小时
long hour = between.toHours();
System.out.println("相差:"+hour+"小时");
//间隔分钟
long millis = between.toMillis();
System.out.println("相差:"+millis+"分");
LocalDateTime一些常用API
LocalDateTime now = LocalDateTime.now(); // 2023-01-29T14:35:51.207
int year = now.getYear(); // 2023
Month month = now.getMonth(); // JANUARY
int monthValue = now.getMonthValue(); // 1
int dayOfYear = now.getDayOfYear(); // 29
int dayOfMonth = now.getDayOfMonth(); // 29
DayOfWeek dayOfWeek = now.getDayOfWeek(); // WEDNESDAY
int dayOfWeekValue = dayOfWeek.getValue(); // 3
int hour = now.getHour(); // 14
int minute = now.getMinute(); // 35
int second = now.getSecond(); // 51
long seconds = Instant.now().getEpochSecond(); // 秒时间戳(10位)
long milliSeconds = Instant.now().toEpochMilli(); // 毫秒时间戳(13位)
LocalDateTime dateTimeFromSecond = LocalDateTime.ofInstant(
Instant.ofEpochSecond(seconds), ZoneOffset.ofHours(8)
); // 秒转datetime
LocalDateTime dateTimeFromMilliSecond = LocalDateTime.ofInstant(
Instant.ofEpochMilli(milliSeconds), ZoneOffset.ofHours(8)
); // 毫秒转datetime
这篇博客介绍了如何在Java中比较两个日期的大小,包括使用SimpleDateFormat和Date的传统方法,以及Java8引入的LocalDateTime和Duration类的新特性。通过示例代码展示了如何计算时间差,并提取了LocalDateTime的一些关键API,如获取年份、月份、小时等信息。此外,还提到了时间戳的转换方法。
1458

被折叠的 条评论
为什么被折叠?



