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

后端 未结 9 1784
走了就别回头了
走了就别回头了 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 20:17

    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. HTH

    0 讨论(0)
  • 2020-12-09 20:21

    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();
    
    0 讨论(0)
  • 2020-12-09 20:21

    This assumes times are in UTC or 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; 
    
    0 讨论(0)
提交回复
热议问题