Advertisement
dimipan80

Days between Two Dates (the Best Method!!!)

Aug 20th, 2014
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. /* Write a program to calculate the difference between two dates in number of days.
  2.  * The dates are entered at two consecutive lines in format day-month-year.
  3.  * Days are in range [1…31]. Months are in range [1…12].
  4.  * Years are in range [1900…2100]. */
  5.  
  6. import java.time.LocalDate;
  7. import java.time.format.DateTimeFormatter;
  8. import java.time.temporal.ChronoUnit;
  9. import java.util.Scanner;
  10.  
  11. public class _07_DaysBetweenTwoDates_TheBestMethod {
  12.  
  13.     public static void main(String[] args) {
  14.         // TODO Auto-generated method stub
  15.         Scanner scan = new Scanner(System.in);
  16.         System.out.println("Enter 2 dates exactly in this format [day-month-year]: ");
  17.         String firstInputStr = scan.next();
  18.         String secondInputStr = scan.next();
  19.  
  20.         LocalDate startDate = convertSpecificInputDateStringToLocalDate(firstInputStr);
  21.         LocalDate endDate = convertSpecificInputDateStringToLocalDate(secondInputStr);
  22.  
  23.         long totalDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);
  24.  
  25.         System.out.printf("The number of Days between these 2 dates is: %d !\n",
  26.                 totalDaysBetween);
  27.     }
  28.  
  29.     private static LocalDate convertSpecificInputDateStringToLocalDate(
  30.             String inputStr) {
  31.         // TODO Auto-generated method stub
  32.         DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("d-MM-yyyy");
  33.         return LocalDate.parse(inputStr, dateFormat);
  34.     }
  35.  
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement