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

后端 未结 11 2292
天命终不由人
天命终不由人 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:43

    Here is my answer based on @Ole V. V. answer.

    This also works with Singular.

    private String getDuration(Date d1, Date d2) {
        Duration diff = Duration.between(d1.toInstant(), d2.toInstant());
    
    
        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.toMillis();
    
        StringBuilder formattedDiff = new StringBuilder();
        if(days!=0){
            if(days==1){
                formattedDiff.append(days + " Day ");
    
            }else {
                formattedDiff.append(days + " Days ");
            }
        }if(hours!=0){
            if(hours==1){
                formattedDiff.append(hours + " hour ");
            }else{
                formattedDiff.append(hours + " hours ");
            }
        }if(minutes!=0){
            if(minutes==1){
                formattedDiff.append(minutes + " minute ");
            }else{
                formattedDiff.append(minutes + " minutes ");
            }
        }if(seconds!=0){
            if(seconds==1){
                formattedDiff.append(seconds + " second ");
            }else{
                formattedDiff.append(seconds + " seconds ");
            }
        }
    
    
        return formattedDiff.toString();
    }
    

    It works with a StringBuilder to append everything together.

提交回复
热议问题