Calculating days between two dates with Java

前端 未结 11 1637
天命终不由人
天命终不由人 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条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 05:18

    We can make use of LocalDate and ChronoUnit java library, Below code is working fine. Date should be in format yyyy-MM-dd.

    import java.time.LocalDate;
    import java.time.temporal.ChronoUnit;
    import java.util.*;
    class Solution {
        public int daysBetweenDates(String date1, String date2) {
            LocalDate dt1 = LocalDate.parse(date1);
            LocalDate dt2= LocalDate.parse(date2);
    
            long diffDays = ChronoUnit.DAYS.between(dt1, dt2);
    
            return Math.abs((int)diffDays);
        }
    }
    

提交回复
热议问题