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

后端 未结 9 1816
走了就别回头了
走了就别回头了 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 20: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);
        }
    
    }
    

提交回复
热议问题