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

后端 未结 9 1814
走了就别回头了
走了就别回头了 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

提交回复
热议问题