Java get number of days between dates

Ads
 

Java get number of days between dates

In this section, you will learn how to obtain the number of days between the two described dates.

In this section, you will learn how to obtain the number of days between the two described dates.

Java get number of days between dates

     

In this section, you will learn how to obtain the number of days between the two described dates.

In order to get the number of days between two dates, the given example has set two dates by using the Calendar.set(int year, int month, int date). The months in Java is started from 0 to 11 instead of 1 to 12, therfore we have used 8 for the month September and 9 for the month October. The given dates are 2008,Sep,1 and 2008,Oct,31 respectively.

getTime() method of Calendar class- This method returns the Calendar's time value.

getTime() method of Date class- This method returns the number of milliseconds represented by the date object.

Following code returns the number of days between two dates:

return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));

Here is the code of DateDifference .java

import java.util.*;
 public class DateDifference {
 public static void main(String args[]){
 DateDifference difference = new DateDifference();
 }
 DateDifference() {
 Calendar cal1 = new GregorianCalendar();
 Calendar cal2 = new GregorianCalendar();

 cal1.set(200881); 
 cal2.set(2008931);
 System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
 }
 public int daysBetween(Date d1, Date d2){
 return (int)( (d2.getTime() - d1.getTime()) / (1000 60 60 24));
 }
 }

Output will be displayed as

Download Source Code

Ads

Ads