I know you got your solution from Andreas’ comment already. What I want to do here is take a step back and suggest a few improvements to your code. Feel free to ignore.
- Most importantly I suggest you throw the long outdated classes
Date
, DateFormat
and SimpleDateFormat
overboard and start using their modern replacements. These came out in the java.time
package early in 2014. These also offer a much more straightforward and clear way of calculating the difference.
- Follow the convention that says that a variable name begins with a lowercase letter. Specifically, in the same source file to use a class called
Date
and two variable called date
and Date
is bound to cause confusion.
- Like Henry I also think you intended
difference = Math.abs(difference);
.
- Your calls to
String.valueOf()
are superfluous and just seem to make the code a bit harder to read. Drop them.
For the sake of the example, in the code I suggest below, I am deliberately using your incorrect date format pattern string, dd/MM/YYYY
.
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/YYYY");
LocalDate todayAsLocalDate = LocalDate.parse(today, format);
LocalDate dateAsLocalDate = LocalDate.parse(date, format);
difference = ChronoUnit.DAYS.between(todayAsLocalDate, dateAsLocalDate);
difference = Math.abs(difference);
System.out.println("date " + date);
System.out.println("date " + dateAsLocalDate);
System.out.println("date " + today);
System.out.println("date " + todayAsLocalDate);
System.out.println(difference);
As the code stands now, it throws a java.time.format.DateTimeParseException: Text '20/11/2016' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {WeekBasedYear[WeekFields[SUNDAY,1]]=2016, MonthOfYear=11, DayOfMonth=20},ISO of type java.time.format.Parsed
. When the code is incorrect, I much prefer an exception over an incorrect result that might go unnoticed. So this is better than what SimpleDateFormat
gave you.
While the message is not easy to read, the bit to notice is WeekBasedYear
. Week-based years are only useful with week numbers, you intended none of that. If you compare with the documentation, you will see that uppercase Y
in the pattern is week-based-year while lowercase y
is year-of-era. So let’s correct:
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
Now the code prints:
date 29/11/2016
date 2016-11-29
date 20/11/2016
date 2016-11-20
9
We note one final advantage of the modern classes: you can have a date without a time-of-day when this is what you need, again giving code that models your requirements more precisely and thereby leaves less room for confusion.
Question: can I use the modern classes with my Java version?
If using at least Java 6, you can.