Advertisement
a1m

Days between Two Dates

a1m
Sep 8th, 2015
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. import java.time.LocalDate;
  2. import java.time.format.DateTimeFormatter;
  3. import java.util.Scanner;
  4.  
  5. public class Problem_07_DaysBetweenTwoDates {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         String firstDateAsString = scanner.nextLine();
  10.         String secondDateAsString = scanner.nextLine();
  11.         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MM-yyyy");
  12.         LocalDate date = LocalDate.parse(firstDateAsString, formatter);
  13.         LocalDate date2 = LocalDate.parse(secondDateAsString, formatter);
  14.         long days;
  15.         boolean firstDateIsbeforeSecond = date.isBefore(date2);
  16.       if(firstDateIsbeforeSecond){
  17.           days = countDaysBetweenTwoDates(date, date2);
  18.       }
  19.         else {
  20.           days = countDaysBetweenTwoDates(date2, date);
  21.       }
  22.         if (firstDateIsbeforeSecond) {
  23.             System.out.println(days);
  24.         }
  25.         else{
  26.             System.out.println(-days);
  27.         }
  28.  
  29.     }
  30.  
  31.     private static long countDaysBetweenTwoDates(LocalDate earlierDate, LocalDate laterDate) {
  32.        long days = 0L;
  33.         while (!earlierDate.equals(laterDate)){
  34.             earlierDate = earlierDate.plusDays(1);
  35.             days++;
  36.         }
  37.         return days;
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement