[英]Difference between two Date
I want to find difference between 2 Date in months and days using Java. 我想用Java在几个月和几天里找到2 Date之间的区别。 For example: difference between 5/16/2013 and 7/20/2013 is 2 months and 4 days .
例如: 2013年 5月16日与2013年 7月20日之间的差额是2个月零4天 。
Thank you for your consideration on this matter. 谢谢您对此事的考虑。
Use joda time library as its better to handle dates http://joda-time.sourceforge.net/ 使用更好的joda时间库来处理日期http://joda-time.sourceforge.net/
Something like this Days.daysBetween(first DateTime, second DateTime).getDays();
像这样的
Days.daysBetween(first DateTime, second DateTime).getDays();
Try this one 试试这个
java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date date1 = df.parse("2012-09-30 15:26:14+00");
java.util.Date date2 = df.parse("2012-08-30 15:26:14+00");
int diff = getMonthDifference(date1, date2);
System.out.println(diff);
public static int getMonthDifference(java.util.Date date1, java.util.Date date2) {
if (date1.after(date2)) {
return getMonthDifference0(date1, date2);
} else if (date2.after(date1)) {
return -getMonthDifference0(date2, date1);
}
return 0;
}
private static int getMonthDifference0(java.util.Date date1, java.util.Date date2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(date1);
c2.setTime(date2);
int diff = 0;
while (c2.getTimeInMillis() < c1.getTimeInMillis()) {
c2.add(Calendar.MONTH, 1);
diff++;
}
int dd = c2.get(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DAY_OF_MONTH);
if (dd > 0) {
diff--;
} else if (dd == 0) {
int hd = c2.get(Calendar.HOUR_OF_DAY) - c1.get(Calendar.HOUR_OF_DAY);
if (hd > 0) {
diff++;
} else if (hd == 0) {
long t1 = c1.getTimeInMillis() % (60 * 1000);
long t2 = c2.getTimeInMillis() % (60 * 1000);
if (t2 > t1) {
diff--;
}
}
}
return diff;
}
I would do it like this 我会这样
Calendar c1 = new GregorianCalendar(2012, 0, 1);
Calendar c2 = new GregorianCalendar(2013, 0, 2);
int monthDiff = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
int dayDiff;
if (c1.get(Calendar.DATE) < c2.get(Calendar.DATE)) {
monthDiff--;
dayDiff = c1.getActualMaximum(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DATE) + c2.get(Calendar.DATE);
} else {
dayDiff = c2.get(Calendar.DATE) - c1.get(Calendar.DATE);
}
System.out.println(monthDiff + " " + dayDiff);
Nobody said console.log( new Date("2013-09-30") - new Date("2012-01-01") ); 没有人说console.log(new Date(“ 2013-09-30”)-new Date(“ 2012-01-01”)); It will give you difference in milliseconds.
它会以毫秒为单位给您带来差异。 Its up to you to handle time zones and so forth when creating those 2 objects.
创建这两个对象时,由您自己来处理时区等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.