Android/Java - Date Difference in days

前端 未结 18 1243
感动是毒
感动是毒 2020-11-22 14:17

I am getting the current date (in format 12/31/1999 i.e. mm/dd/yyyy) as using the below code:

Textview txtViewData;
txtViewDate.setText(\"Today is \" +
              


        
18条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 14:39

    There's a simple solution, that at least for me, is the only feasible solution.

    The problem is that all the answers I see being tossed around - using Joda, or Calendar, or Date, or whatever - only take the amount of milliseconds into consideration. They end up counting the number of 24-hour cycles between two dates, rather than the actual number of days. So something from Jan 1st 11pm to Jan 2nd 1am will return 0 days.

    To count the actual number of days between startDate and endDate, simply do:

    // Find the sequential day from a date, essentially resetting time to start of the day
    long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
    long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;
    
    // Find the difference, duh
    long daysBetween = endDay - startDay;
    

    This will return "1" between Jan 2nd and Jan 1st. If you need to count the end day, just add 1 to daysBetween (I needed to do that in my code since I wanted to count the total number of days in the range).

    This is somewhat similar to what Daniel has suggested but smaller code I suppose.

提交回复
热议问题