I copied code from the web for calculating the number of days between two dates. it often produces incorrect results. For example, The days between 01/15/2008 and 03/15/2010 are 790. The code returns 789. The days between 12/30/2013 and 02/28/2017 are 1156. The code returns 1152. Are the errors due to the code or Calendar class? I am copying the code below. This is my first post and I apologize for any protocol errors. Thanks, Nick
import java.util.Calendar;
public class DateExperiment2
{
public static void main(String args[]) throws Exception
{
// Create Calendar instances
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
// Set the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH.
calendar1.set(2008, 1, 15);
calendar2.set(2010, 3, 15);
//Get Calendars' time value in milliseconds
long miliSecondForDate1 = calendar1.getTimeInMillis();
long miliSecondForDate2 = calendar2.getTimeInMillis();
// Calculate the difference in millisecond between two dates
long diffInMilis = miliSecondForDate1 - miliSecondForDate2;
//Convert milliseconds to days
long diffInDays = diffInMilis / (24 * 60 * 60 * 1000);
System.out.println(diffInDays);
}
}
The results and the is good But when you set month on 01
`Calendar.Set(2000,1,15)`
That means you set it on 15 February 2000 Month on Calender start from 0
0 =is January 1= February...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.