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!!!