计算两个日期相差天数

我与影子孤独终老i 提交于 2019-12-04 21:35:00
 /**     * 计算两个日期相差天数     */    public static int compareDays(Date date1, Date date2){        Calendar calendar1 = Calendar.getInstance();        Calendar calendar2 = Calendar.getInstance();        calendar1.setTime(date1);        calendar2.setTime(date2);        int day1 = calendar1.get(Calendar.DAY_OF_YEAR);        int day2 = calendar2.get(Calendar.DAY_OF_YEAR);        int year1 = calendar1.get(Calendar.YEAR);        int year2 = calendar2.get(Calendar.YEAR);        if(year1 > year2) {            int tempyear = year1;            int tempday = day1;            day1 = day2;            day2 = tempday;            year1 = year2;            year2 = tempyear;        }        if (year1 == year2) {            int days = day2 - day1;            System.out.printf("相隔的天数为:%s天", days);            return days;        } else {            int DayCount = 0;            for (int i = year1; i < year2; i++) {                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {                    DayCount += 366;                }else {                    DayCount += 365;                }            }            System.out.printf("相隔的天数为:%s天", DayCount+(day2-day1));            int days = DayCount+(day2-day1);            return days;        }    }    public static void main(String[] args) {        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:m:s");        Date date1 = null;        Date date2 = null;        try {//            date2 = dateFormat.parse("2019-11-18 12:01:32");            date1 = dateFormat.parse("2019-11-16 23:59:32");        } catch (ParseException e) {            e.printStackTrace();        }        int i = compareDays(date1, getCurrentDate());        System.out.println(i);    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!