Java计算两个日期相差的年数、月数、天数

1 借助hutool工具类

hutool maven依赖

         <dependency>
             <groupId>cn.hutool</groupId>
             <artifactId>hutool-all</artifactId>
             <version>5.1.0</version>
         </dependency>

代码实现:

        System.out.println("------- year --------------");
        Date startDateYear = new Date(1553443200000L);
        Date endDateYear = new Date(System.currentTimeMillis());
// 返回相差年数
long betweenYear = DateUtil.betweenYear(startDateYear, endDateYear, true); System.out.println(betweenYear); System.out.println("------- month --------------"); Date startDate = new Date(1553443200000L); Date endDate = new Date(System.currentTimeMillis());
// 返回相差月数
long betweenMonth = DateUtil.betweenMonth(startDate, endDate, true); System.out.println(betweenMonth); System.out.println("------- day --------------"); Date startDateDay = new Date(1553443200000L); Date endDateDay = new Date(System.currentTimeMillis());
// 返回相差天数
long betweenDay = DateUtil.betweenDay(startDateDay, endDateDay, true); System.out.println(betweenDay); System.out.println("------- MS --------------"); Date startDateMs = new Date(1553443200000L); Date endDateMs = new Date(System.currentTimeMillis());
// 返回相差毫秒数
long betweenMs = DateUtil.betweenMs(startDateMs, endDateMs); System.out.println(betweenMs);

通过枚举传参形式实现,包括 week、day、hour、minute、second、ms

        Date startDate = new Date(1553443200000L);
        Date endDate = new Date(System.currentTimeMillis());
// DateUnit.DAY 枚举
long between = DateUtil.between(startDate, endDate, DateUnit.DAY); System.out.println(between);

DateUnit 代码实现:

/**
 * 日期时间单位,每个单位都是以毫秒为基数
 * @author Looly
 *
 */
public enum DateUnit {
    /** 一毫秒 */
    MS(1), 
    /** 一秒的毫秒数 */
    SECOND(1000), 
    /**一分钟的毫秒数 */
    MINUTE(SECOND.getMillis() * 60),
    /**一小时的毫秒数 */
    HOUR(MINUTE.getMillis() * 60),
    /**一天的毫秒数 */
    DAY(HOUR.getMillis() * 24),
    /**一周的毫秒数 */
    WEEK(DAY.getMillis() * 7);
    
    private long millis;
    DateUnit(long millis){
        this.millis = millis;
    }
    
    /**
     * @return 单位对应的毫秒数
     */
    public long getMillis(){
        return this.millis;
    }
}

2  java8实现

     String text1 = "2019-03-25";
        Temporal startDate = LocalDate.parse(text1);
        String text2 = "2022-05-30";
        Temporal endDate = LocalDate.parse(text2);
        System.out.println("------- year --------------");
        // 方法返回为相差年数
        long years = ChronoUnit.YEARS.between(startDate, endDate);
        System.out.println(years);
        System.out.println("------- month --------------");
        // 方法返回为相差月数
        long months = ChronoUnit.MONTHS.between(startDate, endDate);
        System.out.println(months);
        System.out.println("------- day --------------");
        // 方法返回为相差天数
        long days = ChronoUnit.DAYS.between(startDate, endDate);
        System.out.println(days);

更多方法参考 java.time.temporal.ChronoUnit 类中的方法。

 

posted @ 2022-05-30 17:23  明天,你好啊  阅读(12019)  评论(0编辑  收藏  举报