To determine the number of days between two dates, we can employ the Java Calendar class. Let's demonstrate how to use it to calculate the difference between the current date and a specified date in the format yyyy-mm-dd.
Calendar today = Calendar.getInstance(); String specifiedDate = "2010-08-25"; // Parse the specified date string int year = Integer.parseInt(specifiedDate.substring(0, 4)); int month = Integer.parseInt(specifiedDate.substring(5, 7)) - 1; // Months are zero-indexed int day = Integer.parseInt(specifiedDate.substring(8, 10)); Calendar thatDay = Calendar.getInstance(); thatDay.set(year, month, day); // Calculate the difference in milliseconds long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); // Convert milliseconds to days double days = diff / (24 * 60 * 60 * 1000); System.out.println("Number of days between today and " + specifiedDate + ": " + days);
Note:
The above approach provides a rough calculation, and it's generally not advisable to rely solely on it. For more accurate date handling and manipulation, consider using the JodaTime library, which offers a more comprehensive set of date-related operations.
The above is the detailed content of How to Calculate the Difference Between Two Dates in Days using Java?. For more information, please follow other related articles on the PHP Chinese website!