Java,获取两个日期之间的日期 [英] Java, get days between two dates
问题描述
在java中,我想得到两个日期之间的天数,不包括这两个日期。
In java, I want to get the number of days between two dates, excluding those two dates.
例如:
如果第一个日期= 2011年11月11日
,第二个日期= 2011年11月13日
那么它应该是 1
。
If first date = 11 November 2011
and the second date = 13 November 2011
then it should be 1
.
这是我使用的代码,但不起作用( secondDate
和 firstDate
是日历
对象):
This is the code I am using but doesn't work (secondDate
and firstDate
are Calendar
objects):
long diff=secondDate.getTimeInMillis()-firstDate.getTimeInMillis();
float day_count=(float)diff / (24 * 60 * 60 * 1000);
daysCount.setText((int)day_count+"");
我甚至尝试舍入结果,但没有帮助。
I even tried rounding the results but that didn't help.
如何获取java中日期之间的天数,不包括日期?
How do I get the number of days between dates in java excluding the days themselves?
推荐答案
我我刚刚在SDK 8(Android 2.2)上测试了以下代码片段:
I've just tested on SDK 8 (Android 2.2) the following code snippet:
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
date1.clear();
date1.set(
datePicker1.getYear(),
datePicker1.getMonth(),
datePicker1.getDayOfMonth());
date2.clear();
date2.set(
datePicker2.getYear(),
datePicker2.getMonth(),
datePicker2.getDayOfMonth());
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
float dayCount = (float) diff / (24 * 60 * 60 * 1000);
textView.setText(Long.toString(diff) + " " + (int) dayCount);
13,2011 - 2011年11月11日)给出了 dayCount = 2.0
it works perfectly and in both cases (Nov 10,2011 - Nov 8,2011) and (Nov 13,2011 - Nov 11,2011) gives dayCount = 2.0
这篇关于Java,获取两个日期之间的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!