Determining Date Difference in Android/Java
Calculating the difference between two dates is a common requirement in various applications. In Android programming, there are multiple approaches to determine the number of days between the current date and a given date in the format "yyyy/mm/dd."
Using the JodaTime Library
For a reliable and flexible solution, consider utilizing the JodaTime library. It provides robust date handling and manipulation capabilities. Here's an example:
import org.joda.time.LocalDate; import org.joda.time.Period; import org.joda.time.PeriodType; LocalDate today = LocalDate.now(); LocalDate thatDay = LocalDate.parse("1985/08/25"); Period period = new Period(thatDay, today, PeriodType.days()); long days = period.getDays();
This approach uses JodaTime to parse the given date string and calculate the difference in days from today.
Manual Approximation
Alternatively, you can attempt a manual approximation using the following steps:
Example Code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); Date d = formatter.parse("1985/08/25"); Calendar thatDay = Calendar.getInstance(); thatDay.setTime(d); Calendar today = Calendar.getInstance(); long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); long days = diff / (24 * 60 * 60 * 1000);
Note: This manual approximation may not be entirely accurate for dates close to year or month boundaries.
The above is the detailed content of How to Efficiently Calculate the Date Difference in Android/Java?. For more information, please follow other related articles on the PHP Chinese website!