Home >Java >javaTutorial >How to Calculate the Date Difference in Days in Android/Java?

How to Calculate the Date Difference in Days in Android/Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-17 13:26:15640browse

How to Calculate the Date Difference in Days in Android/Java?

Finding Date Difference in Days: Android/Java Approach

You have the current date in the format mm/dd/yyyy and another date in the format yyyy/mm/dd. To calculate the difference between these dates in days, consider the following steps:

// Calculate the difference in milliseconds
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis();

// Convert the difference to days
long days = diff / (24 * 60 * 60 * 1000);

Parsing the Date from a String

To parse the date from the string "yyyy/mm/dd" into a Calendar object, you can use the SimpleDateFormat class:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
    d = formatter.parse(strThatDay); // catch exception
} catch (ParseException e) {
    e.printStackTrace();
}

Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d);

Alternative Method

Since you know the date format, you could also use Integer.parseInt() on its substrings to get their numeric values and perform the calculations directly.

The above is the detailed content of How to Calculate the Date Difference in Days in Android/Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn