我找到了一个非常有用的库,它是日期格式的SimpleDateFormat
。那不是问题。 compareTo
方法用于比较日期,但我的问题是compareTo
没有显示当时之间的差异
例如下面的代码:
String date1 = "Apr 2010";
String date2 = "Jan 2009";
SimpleDateFormat format = new SimpleDateFormat("MMM yy");
Date d1 = null;
Date d2 = null;
d1 = format.parse(date1);
d2 = format.parse(date2);
int test1 = d1.compareTo(d2);
System.out.println(test1);
上面的输出给了我-9
。我可以知道方法compareTo
如何计算它?
我想要的是找出这些月份和年份之间的差异。非常感谢你。
答案 0 :(得分:4)
compareTo
方法继承自Comparable
。它的javadoc陈述
将此对象与指定的订单对象进行比较。返回一个 负整数,零或正整数,因为此对象较少 比,等于或大于指定的对象。
这就是你要从compareTo
获得的所有内容。哪个更大/更小/相等。
如果您想比较日期字段,您需要自己完成。或者使用像Joda Time这样的第三方库。例如
String date1 = "Apr 2010";
String date2 = "Jan 2009";
DateTimeFormatter formatter = DateTimeFormat.forPattern("MMM yyyy");
DateTime d1 = formatter.parseDateTime(date1);
DateTime d2 = formatter.parseDateTime(date2);
Months monthsBetween = Months.monthsBetween(d1, d2);
System.out.println("Months diff: " + monthsBetween.get(DurationFieldType.months()));
Years yearsBetween = Years.yearsBetween(d1, d2);
System.out.println("Years diff: " + yearsBetween.get(DurationFieldType.years()));
打印
Months diff: -15
Years diff: -1
答案 1 :(得分:0)
查看Calendar类。它用于获取和设置实际日期属性,如年,月,日等。这是我最近写的...
public Date addDays(Date date, int deltaDays) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date.getTime());
calendar.add(Calendar.DAY_OF_MONTH, deltaDays);
return new Date( calendar.getTimeInMillis() );
}
public Date getFirstWeekdayOfYear(int dayOfWeek, int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
while (calendar.get(Calendar.DAY_OF_WEEK) != dayOfWeek) {
calendar.add(Calendar.DATE, 1);
}
return new Date( calendar.getTimeInMillis());
}
public boolean isOlderThan(Date date, int days) {
return date.getTime() < getToday(0-days).getTime();
}
答案 2 :(得分:0)
您需要制作日历日历
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = ...
...
然后从日历中获得数年和数月
int y1= c1.get(Calendar.YEAR);
int m1 = c1.get(Calendar.MONTH);
int y2 =
...
现在使用整数运算
找到差异