no of days between days java

kalyandm
kalyandm used Ask the Experts™
on
Friends
Please help me to calculate the number of days between 2 given dates.Please note that The code should not use any date or calendar classes provided by any library.

Input will be via a command line interface
DateTool fromDate toDate
e.g. DateTool 15/03/2007  31/03/2007
Output should be to the console:
e.g. Total number of days difference = 16.
rules
The code validate that both dates are valid.
The code should accept date formats in dd/mm/yy and dd/mm/yyyy formats.
The number of days between the dates should be correct.

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Kamaraj SubramanianApplication Support Analyst

Commented:

static int getDaysBetween (java.util.Calendar d1, java.util.Calendar d2) {
    if (d1.after(d2)) {  // swap dates so that d1 is start and d2 is end
        java.util.Calendar swap = d1;
        d1 = d2;
        d2 = swap;
    }
    int days = d2.get(java.util.Calendar.DAY_OF_YEAR) -
               d1.get(java.util.Calendar.DAY_OF_YEAR);
    int y2 = d2.get(java.util.Calendar.YEAR);
    if (d1.get(java.util.Calendar.YEAR) != y2) {
        d1 = (java.util.Calendar) d1.clone();
        do {
            days += d1.getActualMaximum(java.util.Calendar.DAY_OF_YEAR);
            d1.add(java.util.Calendar.YEAR, 1);
        } while (d1.get(java.util.Calendar.YEAR) != y2);
    }
    return days;
} // getDaysBetween()

Open in new window

Author

Commented:
Hi itkamaraj:
Thanks for your response.As stated in my query the code should not use any date or calendar classes provided by any library.So if you have any other alternatives please let me know.I'm happy to increase points if more effort is needed.

Thanks
Kamaraj SubramanianApplication Support Analyst

Commented:
Hi,

If you dont want to use any calender or any other classes then you have write your own method to do this calculation.

Here is my idea :

1) seperate from date,month and year ( using substring method )
2) then validate all the three values
3) seperate <To> date month and year
4) Check the differnece between years. if you find difference then validate the month difference also.
5) and calculate the no. of days by simple caluculation.

But you need more validation in this method. Please and try and post your solution. Definetly experts will help you.

It seems like a home work.

thanks
kamaraj.s

Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

Here is some example code.  This does NOT take into consider that each month and year has different amount of days.  It just assumes 31 and 365 respectively, but you are fully capable of doing that.  Also, it does not test for year as two-digit.  I did a lot of work for you here!  Use this as a template to help you get started and figure out the rest on your own.  You'll never learn programming without first trying it, and I'm sure that's what your teacher wants.  I hope this helps!  Goodluck.
package javaapplication1;
 
import java.util.Scanner;
 
public class DateDifference {
  public static void main(String[] args) {
    Scanner stdin = new Scanner(System.in);
 
    // Get input from user.
    //   \t = tab
    System.out.print("FromDate:\t");
    String fromDate = stdin.nextLine();
    System.out.println("ToDate:\t");
    String toDate = stdin.nextLine();
 
    // Parse dates.
    MyDate myFromDate = null;
    MyDate myToDate = null;
    try {
      myFromDate = new MyDate(fromDate);
      myToDate = new MyDate(toDate);
    }
    catch(Exception e) {
      System.err.println("ERROR:\tInvalid date(s)!");
      e.printStackTrace();
      stdin.next();
      System.exit(0);
    }
 
 
    // Find date difference!
      // Subtract months.
      // Minus 1 because we just want to count the number of days between the
      //   months.  On the actual month, we have to factor in the day of the
      //   month.  For example, 9/7/2009 and 20/8/2009 are not 31 days apart
      //   because of "9" and "20".
    int monthDifference = (myToDate.getMonth() - myFromDate.getMonth()) - 1;
      //If months are same, it will be -1, so have to check for that.
    if(monthDifference < 0) {
      monthDifference = 0;
    }
      // Convert months to days.
      //   Note each month has different amount of days!
      //   You'll need to modify this algorithm for that!
    monthDifference *= 31; //Assume each month has 31 days.
 
      // Subtract years.
    int yearDifference = myToDate.getYear() - myFromDate.getYear();
      // Convert years to days.
      //   Note each year has different amount of days!
      //   You'll also need to modify this algorithm for that!
    yearDifference *= 365;
 
      // Subtract days.
    int dayDifference = 0;
      // Same month?
    if(myFromDate.getMonth() == myToDate.getMonth()) {
      dayDifference = myToDate.getDay() - myFromDate.getDay();
    }
    else {
      //31 is assumed; this needs to be change depending on month!
      int fromDateDaysInItsMonth = 31 - myFromDate.getDay();
      dayDifference = fromDateDaysInItsMonth + myToDate.getDay();
    }
 
    // Compute and output results
    int dateDifferenceInDays = dayDifference + monthDifference + yearDifference;
    System.out.println("Date Difference in Days:\t" + dateDifferenceInDays);
  }
 
  //Static so that static method "main" can access this class.
  private static class MyDate {
    private int day;
    private int month;
    private int year;
 
    public MyDate(String date) throws Exception {
      //This does not test for backslash (i.e., "\")!
      //  You'll need to re-write this code to do that if you need that
      //  functionality.
      //All of these methods will throw exceptions if it can't perform the
      //  action, so to test for validity, put this in a try...catch block.
      //Note that this class uses the British date format only as you used in
      //  your post!
 
      //Get day
      int indexOfFirstSlash = date.indexOf("/");
      String stringDay = date.substring(0,indexOfFirstSlash);
      stringDay = stringDay.trim(); //Remove unnecessary white space at ends.
      day = Integer.parseInt(stringDay); //Convert day to integer.
      //  You'll need to modify this code!  Google for how to see how many days
      //    are in each month, then come up with an algorithm and perform the
      //    test here.
      if(day < 1 || day > 31) {
        throw(new Exception("ERROR:\tInvalid day!"));
      }
 
      //Get month
      ++indexOfFirstSlash; //Increment this so that the search doesn't find the
                           //  first slash again.
      int indexOfSecondSlash = date.indexOf("/",indexOfFirstSlash);
      String stringMonth = date.substring(indexOfFirstSlash,indexOfSecondSlash);
      stringMonth = stringMonth.trim(); //Remove unnecessary white space at ends.
      month = Integer.parseInt(stringMonth); //Convert month to integer.
      if(month < 1 || month > 12) {
        throw(new Exception("ERROR:\tInvalid month!"));
      }
 
      //Get month
      //  This does not test for yy (i.e., "09")!  You'll need to do that!
      String stringYear = date.substring(indexOfSecondSlash + 1);
      stringYear = stringYear.trim(); //Remove unnecessary white space at ends.
      year = Integer.parseInt(stringYear); //Convert year to integer.
      if(year < 1000 || year > 9999) {
        throw(new Exception("ERROR:\tInvalid year!"));
      }
 
      //For debugging this class, uncomment this line.
      //System.out.println(day + "/" + month + "/" + year);
    }
 
    public int getDay() {
      return(day);
    }
 
    public int getMonth() {
      return(month);
    }
 
    public int getYear() {
      return(year);
    }
  }
}

Open in new window

Author

Commented:
Thanks very much.Yes this will work as head start for me to work on

Thanks

Commented:
Grade changed to 'A'
 
quomodo
Community Support Moderator
I got bored one day and went ahead and did the whole thing.  Why?  I dunno.
package sweet;
 
import java.util.Scanner;
 
/**
 * @author WhiteMage
 */
public class MyDate {
  public static void main(String[] args) {
    System.out.println("MyDate");
    System.out.println("  Input 'exit' to exit the program.");
    Scanner stdin = new Scanner(System.in);
    for(;;) {
      System.out.print("From:  ");
      String fromDate = stdin.nextLine();
      if(fromDate.equalsIgnoreCase("exit")) {
        break;
      }
      System.out.print("To:    ");
      String toDate = stdin.nextLine();
      if(toDate.equalsIgnoreCase("exit")) {
        break;
      }
 
      MyDate myFromDate = null;
      MyDate myToDate = null;
      try {
        myFromDate = new MyDate(fromDate);
        myToDate = new MyDate(toDate);
        System.out.println("From " + myFromDate + " To " + myToDate);
        System.out.println("DAYS:  " + myFromDate.subtractDays(myToDate));
      }
      catch(Exception e) {
        System.out.println("EXCEPTION:  INVALID DATE(S)!");
      }
      System.out.println();
    }
  }
 
  public static final int MONTH_OF_JANUARY = 1;
  public static final int MONTH_OF_FEBRUARY = 2;
  public static final int MONTH_OF_MARCH = 3;
  public static final int MONTH_OF_APRIL = 4;
  public static final int MONTH_OF_MAY = 5;
  public static final int MONTH_OF_JUNE = 6;
  public static final int MONTH_OF_JULY = 7;
  public static final int MONTH_OF_AUGUST = 8;
  public static final int MONTH_OF_SEPTEMBER = 9;
  public static final int MONTH_OF_OCTOBER = 10;
  public static final int MONTH_OF_NOVEMBER = 11;
  public static final int MONTH_OF_DECEMBER = 12;
 
  final String SEPARATOR = "/";
 
  private int day;
  private boolean isValid;
  private int month;
  private int year;
 
  public MyDate(String date) throws Exception {
    isValid = false;
    date = date.replaceAll("\\s",""); //Remove all whitespace
 
    int i = date.indexOf(SEPARATOR);
    if(i < 0) {
      throw(new Exception());
    }
    day = Integer.parseInt(date.substring(0,i));
    if(day < 1) {
      throw(new Exception());
    }
 
    ++i;
    int j = date.indexOf(SEPARATOR,i);
    if(j < 0) {
      throw(new Exception());
    }
    month = Integer.parseInt(date.substring(i,j));
    if(month < 1) {
      throw(new Exception());
    }
 
    ++j;
    year = Integer.parseInt(date.substring(j));
    if(year < 1) {
      throw(new Exception());
    }
 
    if(year > 9999) {
      throw(new Exception());
    }
    if(year < 40) {
      year += 2000;
    }
    else if(year < 100) {
      year += 1900;
    }
 
    i = getDaysInMonth();
    if(i < 1 || day > i) {
      throw(new Exception());
    }
 
    isValid = true;
  }
 
  public int subtractDays(MyDate myToDate) {
    return(subtractDays(this,myToDate));
  }
 
  public static int subtractDays(MyDate myFromDate,MyDate myToDate) {
    if(!myFromDate.isValid() || !myToDate.isValid()
        || myFromDate.getYear() > myToDate.getYear()
        || (myFromDate.getYear() == myToDate.getYear()
            && (myFromDate.getMonth() > myToDate.getMonth()
                || (myFromDate.getMonth() == myToDate.getMonth()
                    && myFromDate.getDay() > myToDate.getDay())))) {
      return(-1);
    }
 
    int days = 0;
 
    if(myFromDate.getYear() == myToDate.getYear()) {
      if(myFromDate.getMonth() == myToDate.getMonth()) {
        days = myToDate.getDay() - myFromDate.getDay();
      }
      else {
        days += (myFromDate.getDaysInMonth() - myFromDate.getDay());
        for(int i = (myFromDate.getMonth() + 1); i < myToDate.getMonth(); i++) {
          days += getDaysInMonth(i,myFromDate.getYear());
        }
        days += myToDate.getDay();
      }
    }
    else {
      days += (myFromDate.getDaysInMonth() - myFromDate.getDay());
      for(int i = (myFromDate.getMonth() + 1); i <= MONTH_OF_DECEMBER; i++) {
        days += getDaysInMonth(i,myFromDate.getYear());
      }
      for(int i = (myFromDate.getYear() + 1); i < myToDate.getYear(); i++) {
        days += getDaysInYear(i);
      }
      for(int i = MONTH_OF_JANUARY; i < myToDate.getMonth(); i++) {
        days += getDaysInMonth(i,myToDate.getYear());
      }
      days += myToDate.getDay();
    }
 
    return(days);
  }
 
  public int getDay() {
    return(day);
  }
 
  public int getDaysInMonth() {
    return(getDaysInMonth(month,year));
  }
 
  public static int getDaysInMonth(int month,int year) {
    switch(month) {
      case MONTH_OF_JANUARY:
      case MONTH_OF_MARCH:
      case MONTH_OF_MAY:
      case MONTH_OF_JULY:
      case MONTH_OF_AUGUST:
      case MONTH_OF_OCTOBER:
      case MONTH_OF_DECEMBER:
        return(31);
      case MONTH_OF_APRIL:
      case MONTH_OF_JUNE:
      case MONTH_OF_SEPTEMBER:
      case MONTH_OF_NOVEMBER:
        return(30);
      case MONTH_OF_FEBRUARY:
        return((isLeapYear(year)) ? 29 : 28);
      default:
        return(0);
    }
  }
 
  public int getDaysInYear() {
    return(getDaysInYear(year));
  }
 
  public static int getDaysInYear(int year) {
    return((isLeapYear(year)) ? 366 : 365);
  }
 
  public int getMonth() {
    return(month);
  }
 
  public int getYear() {
    return(year);
  }
 
  public boolean isLeapYear() {
    return(isLeapYear(year));
  }
 
  public static boolean isLeapYear(int year) {
    return(((year % 4) == 0 && (year % 100) != 0) || (year % 400) == 0);
  }
 
  public boolean isValid() {
    return(isValid);
  }
 
  @Override
  public String toString() {
    if(!isValid()) {
      return("Invalid date.");
    }
    return(day + SEPARATOR + month + SEPARATOR + year);
  }
}

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial