Grails : Difference b/w two dates with fine-grained details

14 / May / 2010 by Amit Jain 4 comments

Hi Friends,

To retrieve difference between two dates with finer details which would display their difference as 2 years 7 weeks 3 days 2 hours 5 mins ago is given below.

 /**
   * Returns differnce b/w new Date and old date as Map holding difference in years, weeks, days, hrs, mins & secs 
   */
  public static Map getDiffernceInDates(Date oldDate, Date newDate = new Date()) {
    Long difference = newDate.time - oldDate.time
    Map diffMap =[:]
    difference = difference / 1000
    diffMap.seconds = difference % 60
    difference = (difference - diffMap.seconds) / 60
    diffMap.minutes = difference % 60
    difference = (difference - diffMap.minutes) / 60
    diffMap.hours = difference % 24
    difference = (difference - diffMap.hours) / 24
    diffMap.years = (difference / 365).toInteger()
    if(diffMap.years)
       difference = (difference) % 365
    diffMap.days = difference % 7
    diffMap.weeks = (difference - diffMap.days) / 7  
    return diffMap
  }
  

The taglib to display the date difference in detail is given below

def timeDiffInDetail = {attrs ->
        Map diff = DateUtil.getDiffernceInDates(attrs.oldDate, attrs.newDate ?: new Date())
        String result =  diff.years ? diff.years + " years " : ""
        result += diff.weeks ? diff.weeks + " weeks " : ""
        result += diff.days ? diff.days + " days " : ""
        result += diff.hours ? diff.hours + " hours " : ""
        result += diff.minutes ? diff.minutes + " minutes ago" : ""
        if (result)
          out << result
        else
          out << " 0 minutes ago"
}

Hope this helpled!

Cheers!

~~Amit Jain~~
amit@intelligrape.com
http://www.tothenew.com

FOUND THIS USEFUL? SHARE IT

comments (4)

  1. jeet singh parmar

    you can directly use for calculate days or month or week or year –

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

    Reply
  2. Paras

    Iam really appreciate with this blog,and have fulfilled the most of my requirement.But is this possible to find the difference in months from the above code.

    I would be thankful to you if you can provide me some guideline over that.

    Reply

Leave a Reply to Paras Cancel reply

Your email address will not be published. Required fields are marked *