Android/Java - Date Difference in days

前端 未结 18 1176
感动是毒
感动是毒 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: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'
    }
    

提交回复
热议问题