Java, Calculate the number of days between two dates

This question already has an answer here:

  • Calculating the difference between two Java date instances 43 answers

  • Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.

    I would recommend that you use Joda Time, which is a much better API than Date / Calendar . It sounds like you should use the LocalDate type in this case. You can then use:

    int days = Days.daysBetween(date1, date2).getDays();
    

    try this code

         Calendar cal1 = new GregorianCalendar();
         Calendar cal2 = new GregorianCalendar();
    
         SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
    
         Date date = sdf.parse("your first date");
         cal1.setTime(date)
         date = sdf.parse("your second date");
         cal2.setTime(date);
    
        //cal1.set(2008, 8, 1); 
         //cal2.set(2008, 9, 31);
         System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
    

    this function

         public int daysBetween(Date d1, Date d2){
                 return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
         }
    

    In Java 8. You can use instances of Enum ChronoUnit to calculate amount of time in different units (days,months, seconds).

    For Example:

    ChronoUnit.DAYS.between(startDate,endDate)
    
    链接地址: http://www.djcxy.com/p/9218.html

    上一篇: 确定两个日期范围是否重叠

    下一篇: Java,计算两个日期之间的天数