【问题标题】:Android difference between two dates?两个日期之间的Android差异?
【发布时间】:2016-10-19 06:52:33
【问题描述】:

我从日历中得到两个日期。它写入一个字符串生成器。我想得到两个日期之间的差异,我还想保持时间之间剩余的天数,周末除外。

 private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,  int selectedMonth, int selectedDay) {


            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;

            if (cur == DATE_DIALOG_ID) {
                // set selected date into textview
               permitDate = new StringBuilder().append(day).append(".").append(month + 1).append(".").append(year).append(" ").toString();
                tvDisplayDate.setText("Date : " + permitDate);

            } else {
               startDate = new StringBuilder().append(day).append(".").append(month + 1) .append(".").append(year).append(" ").toString();
                tvDisplayDate2.setText("Date : " + startDate);


            }

        }
    };

【问题讨论】:

  • 这样认为你应该使用java的日历API
  • 我可以不使用 API 日历吗?
  • 不要试图重新发明轮子。建立在现有解决方案的基础上。像 AndroidThreeTenBp 或 Joda-time。你会减少用头撞墙的次数。
  • 为什么要在没有日历 API 的情况下这样做?

标签: java android datapicker


【解决方案1】:
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);

Calendar today = Calendar.getInstance();

long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis

long days = diff / (24 * 60 * 60 * 1000);

要从字符串中解析日期,您可以使用

String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
 d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
} 


Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....

【讨论】:

    【解决方案2】:

    使用JodaTime 库查找日期之间的差异。 有关更多信息,请按照说明Use Joda Time。

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多