Bugasur
Bugasur

Reputation: 101

Not gettin correct Days diff betweentwo dates of different year

I am using java code to find the days diff. between two dates let say '12/27/16' and '01/01/17'

Code is:

SimpleDateFormat format = new SimpleDateFormat("mm/dd/yy");

Date d1= format.parse("12/27/16");
Date d2=format.parse("01/01/17");

long diff = d1.getTime()-d2.getTime();
long diffDays= diff / (24*60*60*1000);

But when I print diffDays then i am getting 352 days rather 6 days

Upvotes: 0

Views: 64

Answers (2)

James Fry
James Fry

Reputation: 1153

As @Thomas and @nbokmans answered, the dates are the wrong way round (but the code can be easily changed to ignore this). However, Java has a lot of convenience classes for dealing with times and dates that are not well known. I would replace the explicit calculation with one of the following:

    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yy");

    Date d1 = format.parse("12/27/16");
    Date d2 = format.parse("01/01/17");

    long days1 = TimeUnit.MILLISECONDS.toDays(d2.getTime() - d1.getTime());
    long days2 = Duration.between(d1.toInstant(), d2.toInstant()).abs().toDays();
    long days3 = ChronoUnit.DAYS.between(d1.toInstant(), d2.toInstant());

Upvotes: 1

Thomas
Thomas

Reputation: 181745

If you print d1, you'll see:

Wed Jan 27 00:12:00 CET 2016

That's definitely not what you put in. The reason is that your format string is wrong: m means minutes, not month. The correct format is "M/d/y".

And, as @nbokmans already noted, d1 - d2 is backwards and should be d2 - d1.

See also the documentation for SimpleDateFormat.

Upvotes: 2

Related Questions