简体   繁体   English

如何在java或groovy中查找两个日期之间的天数?

[英]How to find the number of days between two dates in java or 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. 但是我要求9th feb 2011 to 19th feb 2011应该返回我11天,无论是秒还是毫秒考虑。 How can I achieve this? 我怎样才能做到这一点?

For the groovy solution you asked for you should consider using this: 对于你要求的groovy解决方案,你应该考虑使用这个:

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 . 如果您运行此示例,它将打印7 You can also enhance this method by using before() and after() to enable inverted dates. 您还可以使用before()after()来启用反转日期来增强此方法。

It's a well worn line, but for Dates use JodaTime . 这是一个很好的线,但对于日期使用JodaTime

Here's how to calculate date intervals using JodaTime. 以下是使用JodaTime 计算日期间隔的方法。

Days days = Days.daysBetween(new DateTime(millis1), new DateTime(millis2));
int daysBetweenDates = days.getDays();
  GregorianCalendar cal1 = new GregorianCalendar(2011,2,9); 
  GregorianCalendar cal2 = new GregorianCalendar(2011,2,19); 
  long ms1 = cal1.getTime().getTime(); 
  long ms2 = cal2.getTime().getTime(); 
  long difMs = ms2-ms1; 
  long msPerDay = 1000*60*60*24; 

  double days = difMs / msPerDay;

In groovy all you need is: 在groovy你需要的是:

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): 或者,如果您需要防止两个Date实例之间的顺序颠倒(当第一个操作数早于第二个操作数时,操作返回负数):

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. 上面的示例使用groovy date.minus(date)运算符实现,它返回两个日期之间的天数。

Example groovy shell session: 示例groovy shell会话:

$ 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)
}
Date.metaClass.calculateDays = { Date offset = new Date() ->            
    Long result = null
    Date date = delegate
    use(groovy.time.TimeCategory) {
        result = (offset - date).days as Long
    }            
    result            
}

example of use: 使用示例:

def sdf = new java.text.SimpleDateFormat("yyyy.MM.dd")

sdf.lenient = false

Date date = sdf.parse("2015.10.02")

println date.calculateDays() 

println date.calculateDays(sdf.parse("2015.11.02"))

Find out the number of days in between two given dates: 找出两个给定日期之间的天数:

@Test

public class Demo3 {

    public static void main(String[] args) {
        String dateStr ="2008-1-1 1:21:28";
        String dateStr2 = "2010-1-2 1:21:28";
        SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        SimpleDateFormat format2 = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        try {
            Date date2 = format.parse(dateStr2);
            Date date = format.parse(dateStr);

            System.out.println("distance is :"+differentDaysByMillisecond(date,date2));
        }catch(ParseException e ){
            e.printStackTrace();
        }
    }

//get Days method

    private static int differentDaysByMillisecond(Date date, Date date2) {
        return (int)((date2.getTime()-date.getTime())/1000/60/60/24);
    }

}

只需使用SimpleDateFormat19th feb 2011 9th feb 201119th feb 2011 9th feb 2011 19th feb 2011解析为日期并将其转换为开始和结束毫米并应用您的计算

This assumes times are in UTC or GMT. 假设时间是UTC或GMT。

long day1 = milliseconds1/ (24 * 60 * 60 * 1000);
long day2 = milliseconds2/ (24 * 60 * 60 * 1000);
// the difference plus one to be inclusive of all days
long intervalDays = day2 - day1 + 1; 

Try this: 尝试这个:

DateFormat format = DateFormat.getDateTimeInstance();
    Date completeDate=null;
    Date postedDate=null;

    try
    {
        completeDate = format.parse("18-May-09 11:30:57");
        postedDate = format.parse("11-May-09 10:46:37");
        long res = completeDate.getTime() - postedDate.getTime();

        System.out.println("postedDate: " + postedDate);
        System.out.println("completeDate: " + completeDate);
        System.out.println("result: " + res + '\n' + "minutes: " + (double) res /  (60*1000) + '\n' 
            + "hours: " + (double) res /  (60*60*1000) + '\n' + "days: " + (double) res /  (24*60*60*1000));
    }
    catch (ParseException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

If you want days to be an integer then just remove casting to double. 如果你想将天数作为整数,那么只需删除转换为double。 HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM