我试图在2个日期之间计算日期如下:
>获取当前日期
>获取过去或未来的日期
>计算不同的差异. 1和否2
>以下列格式显示日期
>如果结果是在过去(2天前)或将来(在2天内)
格式将:天,周,月,年
我尝试了不同的方法,但是无法得到我想要的结果.我发现Android DatePicker对话框将日期转换为整数.我还没有找到一种方法来使DatePicket小部件返回日期变量而不是整数.
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view,**int** year,**int** monthOfYear,**int** dayOfMonth) { enteredYear = year; enteredMonth = monthOfYear; enteredDay = dayOfMonth; } };
基于上述,我尝试将系统日期转换为Integer,但是当尝试计算2个日期之间的日期时,这并不真的有效.
private void getSystemDate(){ final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); systemYear = mYear; mMonth = c.get(Calendar.MONTH); systemMonth = mMonth + 1; mDay = c.get(Calendar.DAY_OF_MONTH); systemDay = mDay; }
解决方法
/** * Returns a string that describes the number of days * between dateOne and dateTwo. * */ public String getDateDiffString(Date dateOne,Date dateTwo) { long timeOne = dateOne.getTime(); long timeTwo = dateTwo.getTime(); long oneDay = 1000 * 60 * 60 * 24; long delta = (timeTwo - timeOne) / oneDay; if (delta > 0) { return "dateTwo is " + delta + " days after dateOne"; } else { delta *= -1; return "dateTwo is " + delta + " days before dateOne"; } }
编辑:在另一个线程中看到同样的问题:
how to calculate difference between two dates using java
编辑2:要获取年/月/周,请执行以下操作:
int year = delta / 365; int rest = delta % 365; int month = rest / 30; rest = rest % 30; int weeks = rest / 7; int days = rest % 7;