欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

计算两个日期相差的天数-Java实现

程序员文章站 2022-07-12 17:50:06
...

这里用到了Java的Calendar类,首先创建两个Date类实例对象,然创建两个Calendar类的实例对象,使用Calendar对象的setTime(Date date) 方法分别为每个Calendar对象设置指定的时间,参数就是Date类对象。接下来分别获取两个Calendar对象的年份数和当前年份中的天数,再对年份进行闰年和平年判断,最后把两个日期全部转化成天数来计算

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class IntervalDay {

    public void 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) {
            System.out.printf("相隔的天数为:%s天", (day2 - day1));
        } 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));
            
        }
    }

    public static void main(String[] args) {
        IntervalDay intervalDay = new IntervalDay();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:m:s");
        Date date1 = null;
        Date date2 = null;
        try {
            date2 = dateFormat.parse("2012-08-02 12:01:32");
            date1 = dateFormat.parse("2018-08-07 13:01:32");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        intervalDay .compareDays(date1, date2);
    }
}