Search code examples
javagrailsgroovy

Get difference between two days (minus method)


I've got two dates:

def lastRequestDate = "08-09-2019" (MM-dd-yyyy)

and

def today = new Date().format('MM-dd-yyyy')

I'm trying to get the difference with groovy minus method:

def lastRequestDate = "08-09-2019"
def today =  new Date().format('MM-dd-yyyy')

def difference = today.minus(lastRequestDate)

println "difference: " + difference

but instead of days amount (1), I'm getting today's date: 08-10-2019

Can you tell me what I'm doing wrong?

I saw such a method, but I'm trying to use minus method to get the date difference.:

use(groovy.time.TimeCategory) {
def duration = endDate – startDate
return duration.days
}

Thank you very much in advance!


Solution

  • Try this:

    def format = 'MM-dd-yyyy'
    def simpleDateFormat = new SimpleDateFormat(format)
    
    def lastRequestDate = sdf.parse("08-09-2019")
    def today = new Date()
    
    def difference = today.minus(lastRequestDate)
    
    println "difference: " + difference
    

    The reasoning behind it is what basically @daggett said:

    def today = new Date().format('MM-dd-yyyy') is not returning an actual date, it returns the string representation of today's date in the specified format, so you actually applied the operation on the string and not on the date

    In order to use the minus function, you need to apply it on 2 dates, hence the use of SimpleDateFormat