Java 计算两个日期相差多少年月日

JDK7及以前的版本,计算两个日期相差的年月日比较麻烦。

JDK8新出的日期类,提供了比较简单的实现方法。

/**
     * 计算2个日期之间相差的  相差多少年月日
     * 比如:2011-02-02 到  2017-03-02 相差 6年,1个月,0天
     * @param fromDate YYYY-MM-DD
     * @param toDate YYYY-MM-DD
     * @return 年,月,日 例如 1,1,1
     */
    public static String dayComparePrecise(String fromDate, String toDate){
        
        Period period = Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate));
        
        StringBuffer sb = new StringBuffer();
        sb.append(period.getYears()).append(",")
                .append(period.getMonths()).append(",")
                .append(period.getDays());
        return sb.toString();
    }

一个简单的工具方法,供参考。

简要说2点:

1. LocalDate.parse(dateString) 这个是将字符串类型的日期转化为LocalDate类型的日期,默认是DateTimeFormatter.ISO_LOCAL_DATE即YYYY-MM-DD。

LocalDate还有个方法是parse(CharSequence text, DateTimeFormatter formatter),带日期格式参数,下面是JDK中的源码,比较简单,不多说了,感兴趣的可以自己去看一下源码

 /**
     * Obtains an instance of {@code LocalDate} from a text string using a specific formatter.
     * <p>
     * The text is parsed using the formatter, returning a date.
     *
     * @param text  the text to parse, not null
     * @param formatter  the formatter to use, not null
     * @return the parsed local date, not null
     * @throws DateTimeParseException if the text cannot be parsed
     */
    public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) {
        Objects.requireNonNull(formatter, "formatter");
        return formatter.parse(text, LocalDate::from);
    }

2. 利用Period计算时间差,Period类内置了很多日期计算方法,感兴趣的可以去看源码。Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate));主要也是用LocalDate去做计算。Period可以快速取出年月日等数据。

3. 使用旧的Date对象时,我们用SimpleDateFormat进行格式化显示。使用新的LocalDateTimeZonedLocalDateTime时,我们要进行格式化显示,就要使用DateTimeFormatter

SimpleDateFormat不同的是,DateTimeFormatter不但是不变对象,它还是线程安全的。线程的概念我们会在后面涉及到。现在我们只需要记住:因为SimpleDateFormat不是线程安全的,使用的时候,只能在方法内部创建新的局部变量。而DateTimeFormatter可以只创建一个实例,到处引用。

创建DateTimeFormatter时,我们仍然通过传入格式化字符串实现:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

格式化字符串的使用方式与SimpleDateFormat完全一致。

参考: https://blog.csdn.net/francislpx/article/details/88691386

         https://www.liaoxuefeng.com/wiki/1252599548343744/1303985694703650

原文地址:https://www.cnblogs.com/brithToSpring/p/13497943.html