0

Here's the program:

class DateDiff {
int month[];//stores the number of days in all the months
int d,y,m,n;
DateDiff(int d,int m,int y)    {
    month=new int[]{31,28,31,30,31,30,31,31,30,31,30,31};
    this.d=d;
    this.m=m;
    this.y=y;
    if(isLeap(y))
        month[1]=29;//if year is leap, February has 29 days
    else
        month[1]=28;
    n=0;
}
//function for checking for Leap Year
boolean isLeap(int y3)    {
    if((y3%400==0) || ((y3%100!=0)&&(y3%4==0)))
        return true;
    else
        return false;
}
//function for finding the number of days that have passed from start of the year 
int getDayNum(int d1,int m1,int y1)    {
    int i=0;
    if(isLeap(y1))//February leap year correction
        month[1]=29;
    else
        month[1]=28;
    for(;i<m1;i++)
        if(d<=month[i]&&i==m1-1)            {
            n+=d1;//add days when month hasn't completed
            break;
        }
        else 
            n+=month[i];  //add the normal number of days in the month
    return n;
}
//finding difference between the dates
int diff(int d2,int m2,int y2)    {
    int daysLeft=getDayNum(d,m,y);//store the number of days passed since start of the year y
    if(isLeap(y))
        daysLeft=366-daysLeft;//subtracting gives the number of days left in year y
    else
        daysLeft=365-daysLeft;
    for(int x=y+1;x<y2;x++)//for subsequent years add 366 or 365 days as required
        if(isLeap(x))
            daysLeft+=366;
        else
            daysLeft+=365;
    daysLeft+=getDayNum(d2,m2,y2);//add the number of days that have passed since start of year y2
    return daysLeft;}}
public class DateDifference{   
 public static int main(int d1,int m1,int y1,int d2,int m2,int y2)    {
        DateDiff obj=new DateDiff(d1,m1,y1);
        return obj.diff(d2,m2,y2);
    }
}

I'm not getting the correct output with this program. Pass d1=20,m2=3,y1=1997 and d2=14,m2=2,y2=2015 ( the dates are 20th March 1997 and 14th February 2015).

The correct difference is 6540 days. My program gives 6619 days. Can somebody point out the error please?

Divyanshu Varma
  • 122
  • 3
  • 17
  • It looks like you're doing this as some kind of learning exercise, but just in case you didn't know, Java possesses it's own Date API that can do this out of the box. It's best practice to use the tools provided by the language. http://docs.oracle.com/javase/7/docs/api/java/util/Date.html – Mapsy Feb 14 '15 at 11:26
  • OP may also be interested in utilising either the joda-time library or the newer java.time API provided by Java 8: http://stackoverflow.com/questions/12032051/differences-between-java-util-date-and-joda-time-apis – Michal M Feb 14 '15 at 12:02
  • @Alex T. Yes this is a learning exercise. I do know that Java has internal APIs which can do this for me, but I am not to use it as per the instructions of my teacher. I must do it with the basics. – Divyanshu Varma Feb 14 '15 at 12:08
  • Use LocalDate and Period classes from java 8. Check my answers below – Emmanuel Osimosu Oct 15 '16 at 10:00

4 Answers4

1
public DateDiff(int d,int m,int y){
    m--;

public int diff(int d2,int m2,int y2)    {
    m2--;

At some places you must adjust for the "human" form of month numbers 1-12 to the internal form 0-11 you have chosen.

Add public and private to all calls depending on whether you do and don't adjust the month.

Later More fixes

Remove these lines. They are in a useless place.

if(isLeap(y))
    month[1]=29;//if year is leap, February has 29 days
else
    month[1]=28;
n=0;

Don't use a field for a local sum. (int n).

int getDayNum(int d1,int m1,int y1)    {
  if(isLeap(y1))//February leap year correction
    month[1]=29;
  else
    month[1]=28;
  int n = 0;
  for(int i = 0; i<m1; i++){
    n += month[i];
  }
  n += d1;//add days when month hasn't completed
  return n;
}

The loop construction is ill-advised. No if!

Some improvements in coding style:

class DateDiff
  int month[] = new int[]{31,28,31,30,31,30,31,31,30,31,30,31};
  int d,y,m;
  DateDiff(int d,int m,int y)    {
    this.d=d;
    this.m=m-1;
    this.y=y;
  }
  boolean isLeap(int y3)    {
    return (y3%400==0) || ((y3%100!=0)&&(y3%4==0));
  }
  int getDayNum(int d1,int m1,int y1){
    month[1] = isLeap(y1) ? 29 : 28;
    int n = 0;
    for(int i = 0; i < m1; i++){
      n += month[i];
    }
    n += d1;//add days when month hasn't completed
    return n;
  }
  int diff(int d2,int m2,int y2){
    m2--;
    int daysLeft = -getDayNum(d,m,y);
    for( int x = y; x<y2; x++ ){
      daysLeft += isLeap(x) ? 366 : 365;
    }
    daysLeft += getDayNum(d2,m2,y2);
    return daysLeft;
  }
}
laune
  • 31,114
  • 3
  • 29
  • 42
  • 1
    Use a debugger to see where incorrect values come up. I've fixed the program, but it still isn't good. – laune Feb 14 '15 at 13:36
  • Thank you very much, the program is working now. Also, now I have replaced m1 with - - m1 in the object creation line of the main method. Similarly, m2 has been replaced by - - m2 on the following line. There is now no need to decrement m1 and m2 within any other method. – Divyanshu Varma Feb 14 '15 at 14:02
0
import java.util.Calendar;

public class DateExample {

    public long diff(int d1, int m1, int y1, int d2, int m2, int y2) {

        long days = 0;
        try {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.set(y1, m1, d1);

            Calendar calendar2 = Calendar.getInstance();
            calendar2.set(y2, m2, d2);

            long diff = calendar2.getTimeInMillis()
                    - calendar1.getTimeInMillis();
            days = (diff / (1000 * 60 * 60 * 24));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return days;

    }

    public static void main(String[] args) {
        DateExample dateExample = new DateExample();
        System.out.println(dateExample.diff(20, 3, 1997, 14, 2, 2015));
    }
}
Arun Kumar
  • 2,874
  • 1
  • 18
  • 15
0

first, i don't think 6540 is the correct difference. however i can offer you two solutions which are consistent with each other. first in java and second in javascript. For your case both programs output 6537.

1) JAVA :

int trhFark(String w_trh_1, String w_trh_2) {                               //YYYYMMDD
    int w_fark              = Integer.MAX_VALUE;

    if  ( w_trh_1.length() == 8 && w_trh_2.length() == 8 ) {

          String w_GG       = w_trh_1.substring(6, 8);
          String w_AA       = w_trh_1.substring(4, 6);
          String w_YYYY     = w_trh_1.substring(0, 4);
          Calendar c1       = Calendar.getInstance();
          c1.set(Integer.valueOf(w_YYYY).intValue(), Integer.valueOf(w_AA).intValue(), Integer.valueOf(w_GG).intValue());

                 w_GG       = w_trh_2.substring(6, 8);
                 w_AA       = w_trh_2.substring(4, 6);
                 w_YYYY     = w_trh_2.substring(0, 4);
          Calendar c2       = Calendar.getInstance();
          c2.set(Integer.valueOf(w_YYYY).intValue(), Integer.valueOf(w_AA).intValue(), Integer.valueOf(w_GG).intValue());

          w_fark            = (int) Math.floor( (c2.getTimeInMillis() - c1.getTimeInMillis()) / (1000 * 60 * 60 * 24 ) );
    }

    return w_fark;
}

public Main() {
    System.out.println("20141230" + ", " + "20150102" + " => " + trhFark("20141230", "20150102"));
    System.out.println("19970320" + ", " + "20150214" + " => " + trhFark("19970320", "20150214"));
}

2) JAVASCRIPT :

function trhFark(w_trh_1, w_trh_2) {                                      //YYYYMMDD

var w_fark           =  99999;

if  ( w_trh_1.length == 8 && w_trh_2.length == 8 ) {

      var w_GG       = w_trh_1.substr(6, 2);
      var w_AA       = w_trh_1.substr(4, 2);
      var w_YYYY     = w_trh_1.substr(0, 4);
      var d1         = new Date(); d1.setFullYear(parseInt(w_YYYY, 10), parseInt(w_AA, 10), parseInt(w_GG, 10));

          w_GG       = w_trh_2.substr(6, 2);
          w_AA       = w_trh_2.substr(4, 2);
          w_YYYY     = w_trh_2.substr(0, 4);
      var d2         = new Date(); d2.setFullYear(parseInt(w_YYYY, 10), parseInt(w_AA, 10), parseInt(w_GG, 10));

      w_fark         = Math.floor( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24 ) );
}

alert(w_fark);
}
mcevadi
  • 3
  • 3
0

Use LocalDateTime or LocalDate and Period from java.time package.

LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime localDateTime1 = LocalDateTime.now().plusDays(10);

Period period = Period.between(localDateTime.toLocalDate(), localDateTime1.toLocalDate());
System.out.println(period.getDays());  // 10 
Emmanuel Osimosu
  • 5,625
  • 2
  • 38
  • 39