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
Release: 2024-12-17 13:26:15
Original
680 people have browsed it

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template