Difference in days between two dates in Java?

后端 未结 19 1747
爱一瞬间的悲伤
爱一瞬间的悲伤 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;  
    }
    
    0 讨论(0)
  • 2020-11-22 08:57
    import java.util.Calendar;
    import java.util.Date;
    
    public class Main {
        public static long calculateDays(String startDate, String endDate)
        {
            Date sDate = new Date(startDate);
            Date eDate = new Date(endDate);
            Calendar cal3 = Calendar.getInstance();
            cal3.setTime(sDate);
            Calendar cal4 = Calendar.getInstance();
            cal4.setTime(eDate);
            return daysBetween(cal3, cal4);
        }
    
        public static void main(String[] args) {
            System.out.println(calculateDays("2012/03/31", "2012/06/17"));
    
        }
    
        /** Using Calendar - THE CORRECT WAY**/
        public static long daysBetween(Calendar startDate, Calendar endDate) {
            Calendar date = (Calendar) startDate.clone();
            long daysBetween = 0;
            while (date.before(endDate)) {
                date.add(Calendar.DAY_OF_MONTH, 1);
                daysBetween++;
            }
            return daysBetween;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:59

    Illustration of the problem: (My code is computing delta in weeks, but same issue applies with delta in days)

    Here is a very reasonable-looking implementation:

    public static final long MILLIS_PER_WEEK = 7L * 24L * 60L * 60L * 1000L;
    
    static public int getDeltaInWeeks(Date latterDate, Date earlierDate) {
        long deltaInMillis = latterDate.getTime() - earlierDate.getTime();
        int deltaInWeeks = (int)(deltaInMillis / MILLIS_PER_WEEK);
        return deltaInWeeks; 
    }
    

    But this test will fail:

    public void testGetDeltaInWeeks() {
        delta = AggregatedData.getDeltaInWeeks(dateMar09, dateFeb23);
        assertEquals("weeks between Feb23 and Mar09", 2, delta);
    }
    

    The reason is:

    Mon Mar 09 00:00:00 EDT 2009 = 1,236,571,200,000
    Mon Feb 23 00:00:00 EST 2009 = 1,235,365,200,000
    MillisPerWeek = 604,800,000
    Thus,
    (Mar09 - Feb23) / MillisPerWeek =
    1,206,000,000 / 604,800,000 = 1.994...

    but anyone looking at a calendar would agree that the answer is 2.

    0 讨论(0)
  • 2020-11-22 09:00

    Based on @Mad_Troll's answer, I developed this method.

    I've run about 30 test cases against it, is the only method that handles sub day time fragments correctly.

    Example: If you pass now & now + 1 millisecond that is still the same day. Doing 1-1-13 23:59:59.098 to 1-1-13 23:59:59.099 returns 0 days, correctly; allot of the other methods posted here will not do this correctly.

    Worth noting it does not care about which way you put them in, If your end date is before your start date it will count backwards.

    /**
     * This is not quick but if only doing a few days backwards/forwards then it is very accurate.
     *
     * @param startDate from
     * @param endDate   to
     * @return day count between the two dates, this can be negative if startDate is after endDate
     */
    public static long daysBetween(@NotNull final Calendar startDate, @NotNull final Calendar endDate) {
    
        //Forwards or backwards?
        final boolean forward = startDate.before(endDate);
        // Which direction are we going
        final int multiplier = forward ? 1 : -1;
    
        // The date we are going to move.
        final Calendar date = (Calendar) startDate.clone();
    
        // Result
        long daysBetween = 0;
    
        // Start at millis (then bump up until we go back a day)
        int fieldAccuracy = 4;
        int field;
        int dayBefore, dayAfter;
        while (forward && date.before(endDate) || !forward && endDate.before(date)) {
            // We start moving slowly if no change then we decrease accuracy.
            switch (fieldAccuracy) {
                case 4:
                    field = Calendar.MILLISECOND;
                    break;
                case 3:
                    field = Calendar.SECOND;
                    break;
                case 2:
                    field = Calendar.MINUTE;
                    break;
                case 1:
                    field = Calendar.HOUR_OF_DAY;
                    break;
                default:
                case 0:
                    field = Calendar.DAY_OF_MONTH;
                    break;
            }
            // Get the day before we move the time, Change, then get the day after.
            dayBefore = date.get(Calendar.DAY_OF_MONTH);
            date.add(field, multiplier);
            dayAfter = date.get(Calendar.DAY_OF_MONTH);
    
            // This shifts lining up the dates, one field at a time.
            if (dayBefore == dayAfter && date.get(field) == endDate.get(field))
                fieldAccuracy--;
            // If day has changed after moving at any accuracy level we bump the day counter.
            if (dayBefore != dayAfter) {
                daysBetween += multiplier;
            }
        }
        return daysBetween;
    }
    

    You can remove the @NotNull annotations, these are used by Intellij to do code analysis on the fly

    0 讨论(0)
  • 2020-11-22 09:01

    I use this funcion:

    DATEDIFF("31/01/2016", "01/03/2016") // me return 30 days
    

    my function:

    import java.util.Date;
    
    public long DATEDIFF(String date1, String date2) {
            long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000;
            long days = 0l;
            SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); // "dd/MM/yyyy HH:mm:ss");
    
            Date dateIni = null;
            Date dateFin = null;        
            try {       
                dateIni = (Date) format.parse(date1);
                dateFin = (Date) format.parse(date2);
                days = (dateFin.getTime() - dateIni.getTime())/MILLISECS_PER_DAY;                        
            } catch (Exception e) {  e.printStackTrace();  }   
    
            return days; 
         }
    
    0 讨论(0)
  • 2020-11-22 09:02

    I might be too late to join the game but what the heck huh? :)

    Do you think this is a threading issue? How are you using the output of this method for example? OR

    Can we change your code to do something as simple as:

    Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar1.set(<your earlier date>);
        calendar2.set(<your current date>);
        long milliseconds1 = calendar1.getTimeInMillis();
        long milliseconds2 = calendar2.getTimeInMillis();
        long diff = milliseconds2 - milliseconds1;
        long diffSeconds = diff / 1000;
        long diffMinutes = diff / (60 * 1000);
        long diffHours = diff / (60 * 60 * 1000);
        long diffDays = diff / (24 * 60 * 60 * 1000);
        System.out.println("\nThe Date Different Example");
        System.out.println("Time in milliseconds: " + diff
     + " milliseconds.");
        System.out.println("Time in seconds: " + diffSeconds
     + " seconds.");
        System.out.println("Time in minutes: " + diffMinutes 
    + " minutes.");
        System.out.println("Time in hours: " + diffHours 
    + " hours.");
        System.out.println("Time in days: " + diffDays 
    + " days.");
      }
    
    0 讨论(0)
提交回复
热议问题