6 Replies Latest reply on Mar 9, 2009 12:46 PM by 843785

# no of days between two dates

Hi ,
I have to calculate the no of days between two dates:
I have written the below code. but it is returning
No of days:66
``````// Year in YYYY format
SimpleDateFormat simpleDateformat = new SimpleDateFormat("yyyy");
Integer year = Integer.parseInt(simpleDateformat.format(date));

// Construct year's first date based on the year i.e JAN 1st
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, 00);
calendar.set(Calendar.DATE, 01);

// Calculate the no of days between those dates
long diff = date.getTime() - (calendar.getTime()).getTime();
int days = (int)Math.floor(diff / (24 * 60 * 60 * 1000));
System.err.println("No of days:" + days);

SimpleDateFormat format = new SimpleDateFormat("yy");
Integer years = Integer.parseInt(format.format(date));``````
• ###### 1. Re: no of days between two dates
Today is the 68th day of the year. The 1st of january is the first.
I ran the your code. I got the result: 67.
Isn't that as expected?

;-)

BTW: Have a look at the Calendar API. Try to optimize your code.
• ###### 2. Re: no of days between two dates
Hi ,
No, when i ran the code it is coming 66. but i have to get as 68.
Thanks
• ###### 3. Re: no of days between two dates
This will give you 68:
``System.out.println("No of days:" + Calendar.getInstance().get(Calendar.DAY_OF_YEAR) );``
Again. Have a look at the Calendar API.
• ###### 4. Re: no of days between two dates
``System.out.println(date);``
• ###### 5. Re: no of days between two dates
EDIT: solution edited out.

Edited by: phdk on 09-03-2009 10:58
• ###### 6. Re: no of days between two dates
Java has no built-in "give me the difference in days" API methods. One commonly-suggested solution is to get the difference in milliseconds between two dates and, using the number of milliseconds in a day, determine the number of days. Unfortunately, daylight savings time creates some problems with this method, as the following Groovy script demonstrates:
``````#! /usr/bin/groovy

df = new java.text.SimpleDateFormat('yyyy-MM-dd')

// These dates cross DST...
startDate = df.parse('2007-03-10')
endDate = df.parse('2007-03-12')

expectedDifferenceInDays = 2

// Here's the problem with millis:
millisInADay = 1000 * 60 * 60 * 24
differenceInMillis = endDate.time - startDate.time

assert expectedDifferenceInDays != actualDifferenceInDays
assert actualDifferenceInDays < expectedDifferenceInDays``````
Here's a more straightforward solution using Java's Calendar API:
``````#! /usr/bin/groovy

df = new java.text.SimpleDateFormat('yyyy-MM-dd')

// These dates cross DST...
startDate = df.parse('2007-03-10')
endDate = df.parse('2007-03-12')

expectedDifferenceInDays = 2

calendar = Calendar.instance
calendar.time = startDate
actualDifferenceInDays = 0
while (calendar.time.before(endDate)) {
actualDifferenceInDays++
``````import org.joda.time.LocalDate