Home > Java > javaTutorial > body text

How to Calculate the Difference Between Two Dates in Days using Java?

Barbara Streisand
Release: 2024-11-27 09:12:14
Original
481 people have browsed it

How to Calculate the Difference Between Two Dates in Days using Java?

Calculating Date Difference in Days for Android/Java

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

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!

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