Difference in days between two dates in Java?

后端 未结 19 2098
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 08:26

I need to find the number of days between two dates: one is from a report and one is the current date. My snippet:

  int age=calculateDiffer         


        
19条回答
  •  情书的邮戳
    2020-11-22 08:57

    The diff / (24 * etc) does not take Timezone into account, so if your default timezone has a DST in it, it can throw the calculation off.

    This link has a nice little implementation.

    Here is the source of the above link in case the link goes down:

    /** Using Calendar - THE CORRECT WAY**/  
    public static long daysBetween(Calendar startDate, Calendar endDate) {  
      //assert: startDate must be before endDate  
      Calendar date = (Calendar) startDate.clone();  
      long daysBetween = 0;  
      while (date.before(endDate)) {  
        date.add(Calendar.DAY_OF_MONTH, 1);  
        daysBetween++;  
      }  
      return daysBetween;  
    }  
    

    and

    /** Using Calendar - THE CORRECT (& Faster) WAY**/  
    public static long daysBetween(final Calendar startDate, final Calendar endDate)
    {
      //assert: startDate must be before endDate  
      int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;  
      long endInstant = endDate.getTimeInMillis();  
      int presumedDays = 
        (int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);  
      Calendar cursor = (Calendar) startDate.clone();  
      cursor.add(Calendar.DAY_OF_YEAR, presumedDays);  
      long instant = cursor.getTimeInMillis();  
      if (instant == endInstant)  
        return presumedDays;
    
      final int step = instant < endInstant ? 1 : -1;  
      do {  
        cursor.add(Calendar.DAY_OF_MONTH, step);  
        presumedDays += step;  
      } while (cursor.getTimeInMillis() != endInstant);  
      return presumedDays;  
    }
    

提交回复
热议问题