Finding the number of days between 2 dates in java
To get the difference between two dates, the key thing is to turn them into "longs" using the gettime function - an example method is shown below.
public void printDaysBetweenDates()
{
// Create two dates
GregorianCalendar cal1 = new GregorianCalendar(2020, 10, 5); // set to
// 5Nov2020
GregorianCalendar cal2 = new GregorianCalendar(); // Set to now
System.out.println("First Date is " + cal1.getTime());
System.out.println("Second Date is " + cal2.getTime());
long mils = (cal1.getTimeInMillis() - cal2.getTimeInMillis());
long days = Math.abs(mils / 1000 / 60 / 60 / 24);
System.out.println("The number of days is " + days);
}
public void printDaysBetweenDates()
{
// Create two dates
GregorianCalendar cal1 = new GregorianCalendar(2020, 10, 5); // set to
// 5Nov2020
GregorianCalendar cal2 = new GregorianCalendar(); // Set to now
System.out.println("First Date is " + cal1.getTime());
System.out.println("Second Date is " + cal2.getTime());
long mils = (cal1.getTimeInMillis() - cal2.getTimeInMillis());
long days = Math.abs(mils / 1000 / 60 / 60 / 24);
System.out.println("The number of days is " + days);
}
| < Prev | Next > |
|---|
