I have these two strings as input strings
03/12/16
03/14/16
I make a single SimpleDateFormatter object to get the date difference like this
DateFormat formatter = new SimpleDateFormat("MM/dd/yy",Locale.US);
Date dateChkIn = formatter.parse("03/12/16");
System.out.println("Checkin date at nights check - "+dateChkIn.toString());
Date dateChkOut = formatter.parse("03/14/16");
System.out.println("Checkout date at nights check - "+dateChkOut.toString());
Long numberOfNghtsCalc = ((dateChkOut.getTime() - dateChkIn.getTime()) / 86400000L);
System.out.println("number of nigts calculated - "+ numberOfNghtsCalc);
Below is my output in the server
Checkin date at nights check - Sat Mar 12 00:00:00 EST 2016
Checkout date at nights check - Mon Mar 14 00:00:00 EDT 2016
number of nigts calculated - 1
Expected output is number of nigts calculated - 2 Please note the two different Time Zones which returned from the formatter
Update : 13-Mar-2016 is considered as DST changing date. Therefore my calculation is getting wrong. (divide by 86400000L)
I found the solution. I got to know that best solution would be use Joda Time. But with least change in the existing code, I think this tricky way will be better. Please edit this answer if you see any drawbacks.
List<Date> dates = new ArrayList<Date>();
Calendar calendar = new GregorianCalendar();
calendar.setTime(dateChkIn);
Date result = null;
while (calendar.getTime().before(dateChkOut)){
result = calendar.getTime();
dates.add(result);
calendar.add(Calendar.DATE, 1);
}
System.out.println("DAYS CALCULATED BY NEW SOLUTION: " + dates.size());
newNumberOfNghtsCalc = (long) dates.size();
dates.clear();
This has actually reduced the running time!
Time taken for code in Question : 275000 (in nano seconds)
Time taken for New solution: 103000