• Source
    1. /*
    2.  
    3.  
    4. File name : LL.java
    5. Date : 27 March 2013
    6. Author : Shivam Tiwari
    7. Organization : http://mycodedock.blogspot.in/
    8. Description : Calculating number of days between two dates in java
    9.  
    10.  
    11. */
    12.  
    13. //import the Calendar and Date library
    14. import java.util.Calendar;
    15.  
    16. //import scanner library to get inputs
    17. import java.util.Scanner;
    18.  
    19. //this is the main class
    20. public class Main {
    21.  
    22. //this is the main function
    23. public static void main(String[] args) {
    24.  
    25. //create a new Scanner object
    26. Scanner ScannerObj = new Scanner(System.in);
    27.  
    28. //create two calendar instance
    29. Calendar FirstDate = Calendar.getInstance();
    30. Calendar SecondDate = Calendar.getInstance();
    31.  
    32. //integer variables to hold input from user
    33. int FirstDateInputYear, FirstDateInputMonth, FirstDateInputDay, SecondDateInputYear, SecondDateInputMonth, SecondDateInputDay;
    34.  
    35. //get input from user
    36. System.out.println("Enter first date's year STRICTLY in YYYY syntax -");
    37. FirstDateInputYear = ScannerObj.nextInt();
    38.  
    39. System.out.println("Enter first date's month STRICTLY in MM syntax -");
    40. FirstDateInputMonth = ScannerObj.nextInt();
    41.  
    42. System.out.println("Enter first date's day STRICTLY in DD syntax -");
    43. FirstDateInputDay = ScannerObj.nextInt();
    44.  
    45. System.out.println("Enter second date's year STRICTLY in YYYY syntax -");
    46. SecondDateInputYear = ScannerObj.nextInt();
    47.  
    48. System.out.println("Enter second date's month STRICTLY in MM syntax -");
    49. SecondDateInputMonth = ScannerObj.nextInt();
    50.  
    51. System.out.println("Enter second date's day STRICTLY in DD syntax -");
    52. SecondDateInputDay = ScannerObj.nextInt();
    53.  
    54.  
    55. //set these dates in calendar instances
    56. FirstDate.set(FirstDateInputYear, FirstDateInputMonth, FirstDateInputDay);
    57. SecondDate.set(SecondDateInputYear, SecondDateInputMonth, SecondDateInputDay);
    58.  
    59. //get the days in between
    60. int DaysInBetween = daysInBetween(FirstDate.getTimeInMillis(),SecondDate.getTimeInMillis());
    61.  
    62. //print result
    63. System.out.println("The number of days between " + FirstDateInputYear + " " + FirstDateInputMonth + " " + FirstDateInputDay + " and " + SecondDateInputYear + " " + SecondDateInputMonth + " " + SecondDateInputDay + " are " + DaysInBetween + ".");
    64. }
    65.  
    66. //making the daysBetweenTwoDates function
    67. public static int daysInBetween(long f, long s){
    68.  
    69. //24 hours in a day
    70. //60 minutes in each hour
    71. //60 seconds in each minute
    72. //1000 milliseconds in each second
    73. return (int)((s - f)/(1000*60*60*24));
    74. }
    75.  
    76. }
    77.