How to get number of days between two calendar instance?

后端 未结 11 1102
孤城傲影
孤城傲影 2020-12-05 01:58

I want to find the difference between two Calendar objects in number of days if there is date change like If clock ticked from 23:59-0:00 there should be a day

11条回答
  •  死守一世寂寞
    2020-12-05 02:51

    I have the similar (not exact same) approach given above by https://stackoverflow.com/a/31800947/3845798.

    And have written test cases around the api, for me it failed if I passed 8th march 2017 - as the start date and 8th apr 2017 as the end date.

    There are few dates where you will see the difference by 1day. Therefore, I have kind of made some small changes to my api and my current api now looks something like this

       public long getDays(long currentTime, long endDateTime) {
    
    Calendar endDateCalendar;
    Calendar currentDayCalendar;
    
    
    //expiration day
    endDateCalendar = Calendar.getInstance(TimeZone.getTimeZone("EST"));
    endDateCalendar.setTimeInMillis(endDateTime);
    endDateCalendar.set(Calendar.MILLISECOND, 0);
    endDateCalendar.set(Calendar.MINUTE, 0);
    endDateCalendar.set(Calendar.HOUR, 0);
    endDateCalendar.set(Calendar.HOUR_OF_DAY, 0);
    
    //current day
    currentDayCalendar = Calendar.getInstance(TimeZone.getTimeZone("EST"));
    currentDayCalendar.setTimeInMillis(currentTime);
    currentDayCalendar.set(Calendar.MILLISECOND, 0);
    currentDayCalendar.set(Calendar.MINUTE, 0);
    currentDayCalendar.set(Calendar.HOUR,0);
    currentDayCalendar.set(Calendar.HOUR_OF_DAY, 0);
    
    
    long remainingDays = (long)Math.ceil((float) (endDateCalendar.getTimeInMillis() - currentDayCalendar.getTimeInMillis()) / (24 * 60 * 60 * 1000));
    
    return remainingDays;}
    

    I am not using TimeUnit.MILLISECONDS.toDays that were causing me some issues.

提交回复
热议问题