Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the number of days between two dates in java or groovy?

Tags:

java

groovy

I have a method which uses following logic to calculate difference between days.

long diff = milliseconds2 - milliseconds1;
long diffDays = diff / (24 * 60 * 60 * 1000);

but I want for ex, 9th feb 2011 to 19th feb 2011 should return me 11 days irrespective of second or milliseconds consideration. How can I achieve this?

like image 576
maaz Avatar asked Feb 25 '11 11:02

maaz


2 Answers

It's a well worn line, but for Dates use JodaTime.

Here's how to calculate date intervals using JodaTime.

Days days = Days.daysBetween(new DateTime(millis1), new DateTime(millis2));
int daysBetweenDates = days.getDays();
like image 36
Joel Avatar answered Sep 16 '22 12:09

Joel


For the groovy solution you asked for you should consider using this:

use(groovy.time.TimeCategory) {
   def duration = date1 - date2
   println "days: ${duration.days}, Hours: ${duration.hours}"
}

It's very easy to understand and extremely readable. You asked for a example how this can be used in an easy method which calculates the days between two dates. So here is your example.

class Example {

    public static void main(String[] args) {
        def lastWeek = new Date() - 7;
        def today = new Date()

        println daysBetween(lastWeek, today)
    }

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

If you run this example it will print you 7. You can also enhance this method by using before() and after() to enable inverted dates.

like image 195
Christopher Klewes Avatar answered Sep 17 '22 12:09

Christopher Klewes