Calculating days between two dates with Java

前端 未结 11 1531
天命终不由人
天命终不由人 2020-11-22 04:42

I want a Java program that calculates days between two dates.

  1. Type the first date (German notation; with whitespaces: \"dd mm yyyy\")
  2. Type the second
11条回答
  •  梦毁少年i
    2020-11-22 05:03

    Most / all answers caused issues for us when daylight savings time came around. Here's our working solution for all dates, without using JodaTime. It utilizes calendar objects:

    public static int daysBetween(Calendar day1, Calendar day2){
        Calendar dayOne = (Calendar) day1.clone(),
                dayTwo = (Calendar) day2.clone();
    
        if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
            return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
        } else {
            if (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
                //swap them
                Calendar temp = dayOne;
                dayOne = dayTwo;
                dayTwo = temp;
            }
            int extraDays = 0;
    
            int dayOneOriginalYearDays = dayOne.get(Calendar.DAY_OF_YEAR);
    
            while (dayOne.get(Calendar.YEAR) > dayTwo.get(Calendar.YEAR)) {
                dayOne.add(Calendar.YEAR, -1);
                // getActualMaximum() important for leap years
                extraDays += dayOne.getActualMaximum(Calendar.DAY_OF_YEAR);
            }
    
            return extraDays - dayTwo.get(Calendar.DAY_OF_YEAR) + dayOneOriginalYearDays ;
        }
    }
    

提交回复
热议问题