Home Java Java-get-example Java get number of days between dates
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Java get number of days between dates

Advertisement
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

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 1, 2008

Related Tutorials

Ask Questions?    Discuss: Java get number of days between dates   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Saravanan
February 16, 2012
Java proram to convert number in to words

Respected Sir, How to convert numbers in to words using java program? For eg: if we type 1234 as input it will display one thousand two hundred and thirty four.
Serge
March 9, 2012
DST

It won't work with DST, saying before and after day saving time chage
F.Bourel
April 4, 2012
Java get number of days between dates

This will not work with dayLight savings zone ...
Daniel
May 15, 2012
Bad code

Your code won't work for many timezones as they have daylight saving time. Which results in 3600000 more milliseconds (1 hour) per day, depending on the date.
DMCA.com