Java比较两个时间的大小

这篇博客介绍了如何在Java中比较两个日期的大小,包括使用SimpleDateFormat和Date的传统方法,以及Java8引入的LocalDateTime和Duration类的新特性。通过示例代码展示了如何计算时间差,并提取了LocalDateTime的一些关键API,如获取年份、月份、小时等信息。此外,还提到了时间戳的转换方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

老规矩话不多说直接上代码:

老办法: 我们通常使用这种办法来比较两个时间的大小

​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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值