Calculate difference between two dates

Hello guys,

I want to calculate difference between two days. I have seen enough things in internet, but nothing helped me…

def currentDate = new Date()
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd")
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd")
try {
	Date datee = format.parse(currentDate)
	Date datee2 = format.parse(model.nextInstallmentDate)
	println ("distance is: " + differentDaysByMillisecond(datee, datee2))
catch (Exception e) {
	println e

public int differentDaysByMillisecond(Date datee, Date datee2) {
	return (int)((datee2.getTime()-datee.getTime()) /1000/60/60/24)

I’ve seen this code on stackoverflow, but it does not work.

I’ve run into this problem before. Luckily, since Java 8 it’s fairly easy to resolve:

LocalDate date1 = LocalDate.of(2019, 8, 7)
LocalDate date2 = LocalDate.of(2019, 8, 6)
Period period = Period.between(date1, date2)
int difference = period.getDays()
assert difference == 1

Hmm, but I should give parameters manually ?
I should take current date and second date comes from API.

You can construct a LocalDate in a number of ways. See the documentation for more info.

(check out the parse() methods in particular)

1 Like

Thanks @Brandon_Hein.

1 Like