如何在java或groovy中找到两个日期之间的天数? [英] How to find the number of days between two dates in java or groovy?

查看:16
本文介绍了如何在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);

但我想例如,2011 年 2 月 9 日至 2011 年 2 月 19 日 应该返回我 11 天,而不管秒或毫秒的考虑.我怎样才能做到这一点?

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?

推荐答案

对于你要求的常规解决方案,你应该考虑使用这个:

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
        }
    }
}

如果你运行这个例子,它会打印你7.您还可以通过使用 before()after() 来增强此方法以启用倒转日期.

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.

这篇关于如何在java或groovy中找到两个日期之间的天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆