0

I have noted error in bellow code when trying calculate days between two dates. There isn't right with month February,

Here is code,

public class NewClass {

    public int numberOfDays(String fromDate,String toDate)
    {    
   java.util.Calendar cal1 = new java.util.GregorianCalendar();
   java.util.Calendar cal2 = new java.util.GregorianCalendar();


   StringBuffer sBuffer = new StringBuffer(fromDate);


   String yearFrom = sBuffer.substring(6,10);
   String monFrom = sBuffer.substring(0,2);
   String ddFrom = sBuffer.substring(3,5);



   int intYearFrom = Integer.parseInt(yearFrom);
   int intMonFrom = Integer.parseInt(monFrom);
   int intDdFrom = Integer.parseInt(ddFrom);


   cal1.set(intYearFrom, intMonFrom, intDdFrom);


   StringBuffer sBuffer1 = new StringBuffer(toDate);


   String yearTo = sBuffer1.substring(6,10);
   String monTo = sBuffer1.substring(0,2);
   String ddTo = sBuffer1.substring(3,5);


   int intYearTo = Integer.parseInt(yearTo);
   int intMonTo = Integer.parseInt(monTo);
   int intDdTo = Integer.parseInt(ddTo);


   cal2.set(intYearTo, intMonTo, intDdTo);

   int days = daysBetween(cal1.getTime(),cal2.getTime());
   return days;
     }


      public int daysBetween(Date d1, Date d2)
      {

  return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
   }


  public static void main(String[] args) throws ParseException {

      String s1 = "02-28-2015"; 
      String s2 = "03-01-2015";

       int num=numberOfDays(s1, s2);
       System.out.println(num);

}

 }

If we gives above dates for varialbe s1 and s2, result is 4. But answer is wrong because 2015 February has only 28 days.

I think problem is this function part (1000 * 60 * 60 * 24)

If anyone knows what to do with this, please update this code or give me some help!!!

  • 3
    Don't, just don't do `(int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));` this is probably the most horrible thing you could do. If you're using Java 8, use the new Time API, otherwise use JodaTime. Also, `Calendar` months start at `0`, not `1`... – MadProgrammer Mar 11 '15 at 06:24

1 Answers1

0

Don't ever try and use the millisecond difference between two times to calculate the differences, there are just to many idiosyncrasies with date/time calculations which can cause all sorts of erroneous errors.

Instead, save yourself (alot) of time and use a dedicated library

Java 8

LocalDate start = LocalDate.of(2015, Month.JANUARY, 1);
LocalDate end = LocalDate.now();

long days = ChronoUnit.DAYS.between(start, end);
System.out.println(days);

Which outputs 69

JodaTime

DateTime startDate = new DateTime(2015, DateTimeConstants.JANUARY, 1, 0, 0);
DateTime endDate = new DateTime();

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
System.out.println(days);

Which outputs 69

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366