java计算日期差,用几年几天表示,不要展示月

java计算日期差,用几年几天表示,不要展示月 (比如:相差10年364天)

下有代码,可直接复制使用。如有帮助,敬请采纳,你的采纳是我前进的动力,O(∩_∩)O谢谢!!!!!!!!
路过的朋友也可以点个赞~(≧▽≦)/~

使用的时候记得修改包名和类名,使用的时候记得修改包名和类名

package Test.Demo;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GetDiffTime {
    public static void main(String[] args) {

        String st = "2004-02-28";// 开始时间
        String et = "2005-03-2";// 结束时间
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date d1 = df.parse(st);
            Date d2 = df.parse(et);

            int sy = Integer.valueOf(st.split("-")[0]);
            int sm = Integer.valueOf(st.split("-")[1]);

            int ey = Integer.valueOf(et.split("-")[0]);
            int em = Integer.valueOf(et.split("-")[1]);

            long diff = d2.getTime()-d1.getTime();

            //判断有多少个闰月在区间内
            int num_runyue = 0;
            for (int i = sy; i < ey + 1; i++) {
                if (i % 4 == 0) {
                    num_runyue++;
                }
            }
            // 闰月不在起始年的月范围
            if (sm >=2 && sy % 4 == 0) {
                num_runyue--;
            }
            // 闰月不在结束始年的月范围
            if (em <= 2 && ey % 4 == 0) {
                num_runyue--;
            }

            long days = diff / (1000 * 60 * 60 * 24);
            // 把所有年都整理成365天
            days = days - num_runyue;

            System.out.println("相差"+days/365+"年"+days%365+"天");
        } catch (Exception e) {
            System.out.println("异常报错");
        }
    }

}

提供思路:
比如日期A小于日期B:
1、比较两个时间的月日大小,不比较年;
2、如果B的月日大于等于A,继续往下走,否则跳到5;
3、用B的年份减去A的年份,计算出差几年;
4、将A的年份设置为B的年份,然后用B减去A计算出差多少天「结束」。
5、用B的年份减去A的年份再减1,计算出差几年;
6、将A的年份设置为B的年份减1,然后用B减去A计算出差多少天「结束」。
实现如下:

LocalDate small = LocalDate.of(2021, 7, 23);
LocalDate big = LocalDate.now();
// 声明年、日
int distanceYears = 0;
long distanceDays = 0;
// 比较月日大小
LocalDate smallWithBigYear = LocalDate.of(big.getYear(), small.getMonth(), small.getDayOfMonth());
// 如果大时间月日大于小时间
if (big.compareTo(smallWithBigYear) >= 0) {
    // 计算差了多少年
    distanceYears = big.getYear() - small.getYear();
    // 计算差了多少天
    distanceDays = big.toEpochDay() - smallWithBigYear.toEpochDay();
} else {
    // 计算差了多少年
    distanceYears = big.getYear() - small.getYear() - 1;
    // 计算差了多少天
    distanceDays = big.toEpochDay() - smallWithBigYear.minusYears(1).toEpochDay();
}
System.out.println(small + " 与 " + big + " 相差 " + distanceYears + " 年 " + distanceDays + " 天");

用Period,ChronoUnit类辅助,先计算两个日期差多少天,多少年,最后将年换算成天数,从总天数中减去年换算的天数即可。这是比较简单的方法。
复杂的,可以用数学公式,强行计算差多少年,多少天。需要考虑闰年、大月、小月的问题。

给你个思路
将两个日期转化成时间戳,然后相减

    /**
     * 相差天数计算
     */
    public int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

天数求出来了,然后你自己会处理成年日把?

第二种,jdk8


        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);

这是我的代码,希望满足您的要求


public static void main(String[] args) {
        String start = "2021-09-25";
        String end = "2022-05-30";
        LocalDate startDate = LocalDate.parse(start);
        LocalDate endDate = LocalDate.parse(end);
        // 开始日期所在年第一天
        LocalDate startDateOfYear = startDate.with(TemporalAdjusters.firstDayOfYear());
        // 开始日期距离所在年第一天有多少天
        long startdays = ChronoUnit.DAYS.between(startDateOfYear, startDate);
        // 结束日期所在年第一天
        LocalDate endDateOfYear = endDate.with(TemporalAdjusters.firstDayOfYear());
        // 结束日期距离所在年第一天有多少天
        long enddays = ChronoUnit.DAYS.between(endDateOfYear, endDate);

        // 结束日期与当年首天相差天数大于开始日期与当年首天相差天数
        if (enddays > startdays) {
            System.out.println(String.format("相差%d年%d天", endDate.getYear() - startDate.getYear(), enddays - startdays));
            return;
        }
        // 结束日期向前借一年,算出借的一年多少天
        int borrowDays = endDate.minusYears(1L).with(TemporalAdjusters.lastDayOfYear()).getDayOfYear();
        System.out.println(String.format("相差%d年%d天", endDate.getYear() - startDate.getYear() - 1, borrowDays + enddays - startdays));
    }

您的采纳就是对我最大的动力,谢谢!!!

img

我的思路是计算四个时间戳,先计算出两个时间点的时间戳然后根据时间戳得到年份然后相减,这就算出了间隔多少年

然后再生成两个时间戳:前一个时间节点的年末(12月31日23:59:59)后一个时间点的年初(1月1日 00:00:00)然后分别计算前一个时间节点和年末差多少天、后一个时间节点和年初差多少天

这个方法好处是不需要考虑闰年大小月的问题

给你提供个思路:1、计算出两个日期相差的天数(这个相对简单,可以使用hutool相关工具类即可)
2、你可以根据日期的年份,然后循环计算出当年的天数,然后将所有天数相加和你计算出的天数比较
3、通过第二步的计算,拼接成字符串即可

2.1 A时间到B时间,相差多少年,月,日。
/**

  • 计算2个日期之间相差的 相差多少年月日
  • 比如:2011-02-02 到 2017-03-02 相差 6年,1个月,0天
  • @param fromDate
  • @param toDate
  • @return
  • /
    public static DayCompare dayComparePrecise(Date fromDate,Date toDate){
    Calendar from = Calendar.getInstance();
    from.setTime(fromDate);
    Calendar to = Calendar.getInstance();
    to.setTime(toDate);
    int fromYear = from.get(Calendar.YEAR);
    int fromMonth = from.get(Calendar.MONTH);
    int fromDay = from.get(Calendar.DAY_OF_MONTH);
    int toYear = to.get(Calendar.YEAR);
    int toMonth = to.get(Calendar.MONTH);
    int toDay = to.get(Calendar.DAY_OF_MONTH);
    int year = toYear - fromYear;
    int month = toMonth - fromMonth;
    int day = toDay - fromDay;
    return DayCompare.builder().day(day).month(month).year(year).build();
    }

2.2 A时间到B时间, 相差年,月,日各是多少
/**

  • 计算2个日期之间相差的 以年、月、日为单位,各自计算结果是多少
  • 比如:2011-02-02 到 2017-03-02
  •                            以年为单位相差为:6年
    
  •                            以月为单位相差为:73个月
    
  •                            以日为单位相差为:2220天
    
  • @param fromDate
  • @param toDate
  • @return
  • /
    public static DayCompare dayCompare(Date fromDate,Date toDate){
    Calendar from = Calendar.getInstance();
    from.setTime(fromDate);
    Calendar to = Calendar.getInstance();
    to.setTime(toDate);
    //只要年月
    int fromYear = from.get(Calendar.YEAR);
    int fromMonth = from.get(Calendar.MONTH);
    int toYear = to.get(Calendar.YEAR);
    int toMonth = to.get(Calendar.MONTH);
    int year = toYear - fromYear;
    int month = toYear * 12 + toMonth - (fromYear * 12 + fromMonth);
    int day = (int) ((to.getTimeInMillis() - from.getTimeInMillis()) / (24 * 3600 * 1000));
    return DayCompare.builder().day(day).month(month).year(year).build();
    }

2.3 A时间到B时间,相差多少年
/**

  • 计算2个日期相差多少年
  • 列:2011-02-02 ~ 2017-03-02 大约相差 6.1 年
  • @param fromDate
  • @param toDate
  • @return
  • /
    public static String yearCompare(Date fromDate,Date toDate){
    DayCompare result = dayComparePrecise(fromDate, toDate);
    double month = result.getMonth();
    double year = result.getYear();
    //返回2位小数,并且四舍五入
    DecimalFormat df = new DecimalFormat("######0.0");
    return df.format(year + month / 12);
    }

推荐一个好用的工具 [](hutool https://hutool.cn/docs/#/core/%E6%97%A5%E6%9C%9F%E6%97%B6%E9%97%B4/%E6%97%A5%E6%9C%9F%E6%97%B6%E9%97%B4%E5%B7%A5%E5%85%B7-DateUtil)
一行代码搞定:

//Level.MINUTE表示精确到分
String formatBetween = DateUtil.formatBetween(between, Level.MINUTE);
//输出:31天1小时
Console.log(formatBetween);