Date Java issue

One Star

Date Java issue

Hello !
This drives me crazy !!!!
I'm trying to define 2 java functions, one to calculate the numbers of days between 2 dates, one to add a certain number of days to a date.
Here are my functions:
    public static int getDateDifferenceInDays (Date firstDate, Date secondDate) {
long diff;
diff = secondDate.getTime() - firstDate.getTime();
diff /= (24L * 3600L * 1000L);
return (int)diff;
public static Date addNumberOfDays (Date referenceDate, int numberOfDays) {
long diff, toAdd;
Date result;
diff = referenceDate.getTime();
diff += numberOfDays * 24L * 3600L * 1000L;
return result;

When I test the functions, by calculating the difference between today and a date to 2009-03-29 it works.
BUT, when I calculate '2009-03-30' - '2009-02-17' it give 40 days (instead of 41)....
I think this is because of a round error (during cast), but... how can I do ??
Seventeen Stars

Re: Date Java issue

perhaps you could find some "good methods" Calendar class in Calendar class like add() method (to add and substract).
but not sure about it
One Star

Re: Date Java issue

Google is your friend:
search: java add days to date
search: java days between 2 dates
Your answer is there for the taking.
One Star

Re: Date Java issue

Yes, it is... but it can also give me some results that looks good at first sight ! Smiley Happy I found many examples where the difference was good if the number of days was less than 40 days, but, when I tried with a date difference that should be 41 days, I got a wrong result (40).
But, I finally found, in the results of your keywords (different from mine). My problem was a round error, solved by adding an hour...
Thank you StijnM

What’s New for Talend Spring ’19

Watch the recorded webinar!

Watch Now

Best Practices for Using Context Variables with Talend – Part 4

Pick up some tips and tricks with Context Variables


How Media Organizations Achieved Success with Data Integration

Learn how media organizations have achieved success with Data Integration


Agile Data lakes & Analytics

Accelerate your data lake projects with an agile approach