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

后端 未结 9 1798
走了就别回头了
走了就别回头了 2020-12-09 19:25

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

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


        
9条回答
  •  眼角桃花
    2020-12-09 19:55

    In groovy all you need is:

    date2 - date1
    

    which returns an integer representing the number of days between the two dates.

    Or if you need to guard against reversal of order between the two Date instances (the operation returns negative numbers when the first operand is earlier than the second):

    Math.abs(date2 - date1)
    

    The above examples use the groovy date.minus(date) operator implementation which returns the number of days between the two dates.

    Example groovy shell session:

    $ groovysh
    Groovy Shell (2.4.8, JVM: 1.8.0_111)
    Type ':help' or ':h' for help.
    
    groovy:000> x = new Date(1486382537168)
    ===> Mon Feb 06 13:02:17 CET 2017
    
    groovy:000> y = new Date(1486000000000)
    ===> Thu Feb 02 02:46:40 CET 2017
    
    groovy:000> x - y
    ===> 4
    

    or if you need a method:

    int daysBetween(date1, date2) {
        Math.abs(date2 - date1)
    }
    

提交回复
热议问题