How do I get difference between two dates in android?, tried every thing and post

后端 未结 11 2261
天命终不由人
天命终不由人 2020-11-28 09:06

I saw all the post in here and still I can\'t figure how do get difference between two android dates.

This is what I do:

long diff = date1.getTime()          


        
相关标签:
11条回答
  • 2020-11-28 09:49

    java.time.Duration

    Use java.time.Duration:

        Duration diff = Duration.between(instant2, instant1);
        System.out.println(diff);
    

    This will print something like

    PT109H27M21S
    

    This means a period of time of 109 hours 27 minutes 21 seconds. If you want someting more human-readable — I’ll give the Java 9 version first, it’s simplest:

        String formattedDiff = String.format(Locale.ENGLISH,
                "%d days %d hours %d minutes %d seconds",
                diff.toDays(), diff.toHoursPart(), diff.toMinutesPart(), diff.toSecondsPart());
        System.out.println(formattedDiff);
    

    Now we get

    4 days 13 hours 27 minutes 21 seconds
    

    The Duration class is part of java.time the modern Java date and time API. This is bundled on newer Android devices. On older devices, get ThreeTenABP and add it to your project, and make sure to import org.threeten.bp.Duration and other date-time classes you may need from the same package.

    Assuming you still haven’t got the Java 9 version, you may subtract the larger units in turn to get the smaller ones:

        long days = diff.toDays();
        diff = diff.minusDays(days);
        long hours = diff.toHours();
        diff = diff.minusHours(hours);
        long minutes = diff.toMinutes();
        diff = diff.minusMinutes(minutes);
        long seconds = diff.toSeconds();
    

    Then you can format the four variables as above.

    What did you do wrong?

    A Date represents a point in time. It was never meant for representing an amount of time, a duration, and it isn’t suited for it. Trying to make that work would at best lead to confusing and hard-to-maintain code. You don’t want that, so please don’t.

    Question: Doesn’t java.time require Android API level 26?

    java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

    • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
    • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
    • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

    Links

    • Oracle tutorial: Date Time, explaining how to use java.time.
    • ThreeTen Backport project, the backport of java.time to Java 6 and 7
    • ThreeTenABP, Android edition of ThreeTen Backport
    • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
    • Java Specification Request (JSR) 310.
    0 讨论(0)
  • 2020-11-28 09:53

    Some addition: Here I convert string to date then I compare the current time.

    String toyBornTime = "2014-06-18 12:56:50";
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
    
        try {
    
            Date oldDate = dateFormat.parse(toyBornTime);
            System.out.println(oldDate);
    
            Date currentDate = new Date();
    
            long diff = currentDate.getTime() - oldDate.getTime();
            long seconds = diff / 1000;
            long minutes = seconds / 60;
            long hours = minutes / 60;
            long days = hours / 24;
    
            if (oldDate.before(currentDate)) {
    
                Log.e("oldDate", "is previous date");
                Log.e("Difference: ", " seconds: " + seconds + " minutes: " + minutes
                        + " hours: " + hours + " days: " + days);
    
            }
    
            // Log.e("toyBornTime", "" + toyBornTime);
    
        } catch (ParseException e) {
    
            e.printStackTrace();
        }
    
    0 讨论(0)
  • 2020-11-28 09:53

    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-28 09:56

    written in Kotlin: if you need difference between 2 dates and don't care about the dates itself ( good if you need to do something in the app,based on time from other operation time that was saved in shared preferences for example). save first time :

    val firstTime:Long= System.currentTimeMillis()
    

    save second time:

    val now:Long= System.currentTimeMillis()
    

    calculate the miliseconds between 2 times:

    val milisecondsSinceLastTime: Long =(now-lastScrollTime)
    
    0 讨论(0)
  • 2020-11-28 09:56

    shortest answer that works for me. send start and end date in millisecond.

    public int GetDifference(long start,long end){
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(start);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int min = cal.get(Calendar.MINUTE);
        long t=(23-hour)*3600000+(59-min)*60000;
    
        t=start+t;
    
        int diff=0;
        if(end>t){
            diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
        }
    
        return  diff;
    }
    
    0 讨论(0)
提交回复
热议问题