Android/Java - Date Difference in days

前端 未结 18 913
感动是毒
感动是毒 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:42

    use these functions

        public static int getDateDifference(int previousYear, int previousMonthOfYear, int previousDayOfMonth, int nextYear, int nextMonthOfYear, int nextDayOfMonth, int differenceToCount){
        // int differenceToCount = can be any of the following
        //  Calendar.MILLISECOND;
        //  Calendar.SECOND;
        //  Calendar.MINUTE;
        //  Calendar.HOUR;
        //  Calendar.DAY_OF_MONTH;
        //  Calendar.MONTH;
        //  Calendar.YEAR;
        //  Calendar.----
    
        Calendar previousDate = Calendar.getInstance();
        previousDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
        // month is zero indexed so month should be minus 1
        previousDate.set(Calendar.MONTH, previousMonthOfYear);
        previousDate.set(Calendar.YEAR, previousYear);
    
        Calendar nextDate = Calendar.getInstance();
        nextDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
        // month is zero indexed so month should be minus 1
        nextDate.set(Calendar.MONTH, previousMonthOfYear);
        nextDate.set(Calendar.YEAR, previousYear);
    
        return getDateDifference(previousDate,nextDate,differenceToCount);
    }
    public static int getDateDifference(Calendar previousDate,Calendar nextDate,int differenceToCount){
        // int differenceToCount = can be any of the following
        //  Calendar.MILLISECOND;
        //  Calendar.SECOND;
        //  Calendar.MINUTE;
        //  Calendar.HOUR;
        //  Calendar.DAY_OF_MONTH;
        //  Calendar.MONTH;
        //  Calendar.YEAR;
        //  Calendar.----
    
        //raise an exception if previous is greater than nextdate.
        if(previousDate.compareTo(nextDate)>0){
            throw new RuntimeException("Previous Date is later than Nextdate");
        }
    
        int difference=0;
        while(previousDate.compareTo(nextDate)<=0){
            difference++;
            previousDate.add(differenceToCount,1);
        }
        return difference;
    }
    
    0 讨论(0)
  • 2020-11-22 14:45

    Use jodatime API

    Days.daysBetween(start.toDateMidnight() , end.toDateMidnight() ).getDays() 
    

    where 'start' and 'end' are your DateTime objects. To parse your date Strings into DateTime objects use the parseDateTime method

    There is also an android specific JodaTime library.

    0 讨论(0)
  • 2020-11-22 14:47

    This is NOT my work, found the answer here. did not want a broken link in the future :).

    The key is this line for taking daylight setting into account, ref Full Code.

    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    

    or try passing TimeZone as a parameter to daysBetween() and call setTimeZone() in the sDate and eDate objects.

    So here it goes:

    public static Calendar getDatePart(Date date){
        Calendar cal = Calendar.getInstance();       // get calendar instance
        cal.setTime(date);      
        cal.set(Calendar.HOUR_OF_DAY, 0);            // set hour to midnight
        cal.set(Calendar.MINUTE, 0);                 // set minute in hour
        cal.set(Calendar.SECOND, 0);                 // set second in minute
        cal.set(Calendar.MILLISECOND, 0);            // set millisecond in second
        
        return cal;                                  // return the date part
    }
    

    getDatePart() taken from here

    /**
     * This method also assumes endDate >= startDate
    **/
    public static long daysBetween(Date startDate, Date endDate) {
      Calendar sDate = getDatePart(startDate);
      Calendar eDate = getDatePart(endDate);
    
      long daysBetween = 0;
      while (sDate.before(eDate)) {
          sDate.add(Calendar.DAY_OF_MONTH, 1);
          daysBetween++;
      }
      return daysBetween;
    }
    

    The Nuances: Finding the difference between two dates isn't as straightforward as subtracting the two dates and dividing the result by (24 * 60 * 60 * 1000). Infact, its erroneous!

    For example: The difference between the two dates 03/24/2007 and 03/25/2007 should be 1 day; However, using the above method, in the UK, you'll get 0 days!

    See for yourself (code below). Going the milliseconds way will lead to rounding off errors and they become most evident once you have a little thing like Daylight Savings Time come into the picture.

    Full Code:

    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.TimeZone;
    
    public class DateTest {
    
    public class DateTest {
    
    static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
    
    public static void main(String[] args) {
    
      TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    
      //diff between these 2 dates should be 1
      Date d1 = new Date("01/01/2007 12:00:00");
      Date d2 = new Date("01/02/2007 12:00:00");
    
      //diff between these 2 dates should be 1
      Date d3 = new Date("03/24/2007 12:00:00");
      Date d4 = new Date("03/25/2007 12:00:00");
    
      Calendar cal1 = Calendar.getInstance();cal1.setTime(d1);
      Calendar cal2 = Calendar.getInstance();cal2.setTime(d2);
      Calendar cal3 = Calendar.getInstance();cal3.setTime(d3);
      Calendar cal4 = Calendar.getInstance();cal4.setTime(d4);
    
      printOutput("Manual   ", d1, d2, calculateDays(d1, d2));
      printOutput("Calendar ", d1, d2, daysBetween(cal1, cal2));
      System.out.println("---");
      printOutput("Manual   ", d3, d4, calculateDays(d3, d4));
      printOutput("Calendar ", d3, d4, daysBetween(cal3, cal4));
    }
    
    
    private static void printOutput(String type, Date d1, Date d2, long result) {
      System.out.println(type+ "- Days between: " + sdf.format(d1)
                        + " and " + sdf.format(d2) + " is: " + result);
    }
    
    /** Manual Method - YIELDS INCORRECT RESULTS - DO NOT USE**/
    /* This method is used to find the no of days between the given dates */
    public static long calculateDays(Date dateEarly, Date dateLater) {
      return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);
    }
    
    /** Using Calendar - THE CORRECT WAY**/
    public static long daysBetween(Date startDate, Date endDate) {
      ...
    }
    

    OUTPUT:

    Manual - Days between: 01-Jan-2007 and 02-Jan-2007 is: 1

    Calendar - Days between: 01-Jan-2007 and 02-Jan-2007 is: 1


    Manual - Days between: 24-Mar-2007 and 25-Mar-2007 is: 0

    Calendar - Days between: 24-Mar-2007 and 25-Mar-2007 is: 1

    0 讨论(0)
  • 2020-11-22 14:47

    tl;dr

    ChronoUnit.DAYS.between( 
        LocalDate.parse( "1999-12-28" ) , 
        LocalDate.parse( "12/31/1999" , DateTimeFormatter.ofPattern( "MM/dd/yyyy" ) ) 
    )
    

    Details

    Other answers are outdated. The old date-time classes bundled with the earliest versions of Java have proven to be poorly designed, confusing, and troublesome. Avoid them.

    java.time

    The Joda-Time project was highly successful as a replacement for those old classes. These classes provided the inspiration for the java.time framework built into Java 8 and later.

    Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

    LocalDate

    The LocalDate class represents a date-only value without time-of-day and without time zone.

    Parsing strings

    If your input strings are in standard ISO 8601 format, the LocalDate class can directly parse the string.

    LocalDate start = LocalDate.parse( "1999-12-28" );
    

    If not in ISO 8601 format, define a formatting pattern with DateTimeFormatter.

    String input = "12/31/1999";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM/dd/yyyy" );
    LocalDate stop = LocalDate.parse( input , formatter );
    

    Elapsed days via ChronoUnit

    Now get a count of days elapsed between that pair of LocalDate objects. The ChronoUnit enum calculates elapsed time.

    long totalDays = ChronoUnit.DAYS.between( start , stop ) ; 
    

    If you are unfamiliar with Java enums, know they are far more powerful and useful that conventional enums in most other programming languages. See the Enum class doc, the Oracle Tutorial, and Wikipedia to learn more.


    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    Where to obtain the java.time classes?

    • Java SE 8 and SE 9 and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
      • See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

    0 讨论(0)
  • 2020-11-22 14:48

    best and easiest way to do this

      public int getDays(String begin) throws ParseException {
         long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
         SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
    
        long begin = dateFormat.parse(begin).getTime();
        long end = new Date().getTime(); // 2nd date want to compare
        long diff = (end - begin) / (MILLIS_PER_DAY);
        return (int) diff;
    }
    
    0 讨论(0)
  • 2020-11-22 14:49

    Joda-Time

    Best way is to use Joda-Time, the highly successful open-source library you would add to your project.

    String date1 = "2015-11-11";
    String date2 = "2013-11-11";
    DateTimeFormatter formatter = new DateTimeFormat.forPattern("yyyy-MM-dd");
    DateTime d1 = formatter.parseDateTime(date1);
    DateTime d2 = formatter.parseDateTime(date2);
    long diffInMillis = d2.getMillis() - d1.getMillis();
    
    Duration duration = new Duration(d1, d2);
    int days = duration.getStandardDays();
    int hours = duration.getStandardHours();
    int minutes = duration.getStandardMinutes();
    

    If you're using Android Studio, very easy to add joda-time. In your build.gradle (app):

    dependencies {
      compile 'joda-time:joda-time:2.4'
      compile 'joda-time:joda-time:2.4'
      compile 'joda-time:joda-time:2.2'
    }
    
    0 讨论(0)
提交回复
热议问题