java 判斷日期是否相同,只判斷年月是否相同
阿新 • • 發佈:2019-02-12
例子中是系統預設的日期格式
public static boolean isSameDate(Date date1, Date date2) {
try {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
boolean isSameYear = cal1.get (Calendar.YEAR) == cal2
.get(Calendar.YEAR);
boolean isSameMonth = isSameYear
&& cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
boolean isSameDate = isSameMonth
&& cal1.get(Calendar.DAY _OF_MONTH) == cal2
.get(Calendar.DAY_OF_MONTH);
return isSameDate;
} catch (Exception e) {
log.error("[RatingEngine] error occurred: ERROR ", e);
}
return false;
}
@Test
public void test8(){
Date date =new Date();
System.out.println(date);
System.out.println(isSameDate(date,new Date()));
}
Tue Oct 17 09:38:24 CST 2017
true
else
public boolean isBeforeMonth(String beforeMonth, String currentMonth) {
// TODO Auto-generated method stub
Date bm=DateUtil.parse(beforeMonth, "yyyy-MM");
Date cm=DateUtil.parse(currentMonth,"yyyy-MM");
Calendar cmCal=Calendar.getInstance();
Calendar bmCal=Calendar.getInstance();
cmCal.setTime(cm);
cmCal.add(Calendar.MONTH,-1);
cm=cmCal.getTime();
bmCal.setTime(bm);
bmCal.getTime();
boolean isSameYear = cmCal.get(Calendar.YEAR) == bmCal
.get(Calendar.YEAR);
boolean isSameMonth = isSameYear
&& cmCal.get(Calendar.MONTH) == bmCal.get(Calendar.MONTH);
/*if(DateUtil.isSameDate(bm, cm)){
return true;
}*/
return isSameMonth;
}