需求实现代码:
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date currDate= new Date();
sdf.format(currDate);
String SUFFIX_TIME_00 ="-01-01";
String SUFFIX_TIME_01 ="-05-16";
String SUFFIX_TIME_02 ="-11-15";
String SUFFIX_TIME_03 ="-12-31";
String SUFFIX_TIME_04 ="1231";
String SUFFIX_TIME_05 ="0630";
String enddate = "";
try {
//Date currDate= sdf.parse("2021-11-16");
String currYear=sdf.format(currDate).substring(0,4);
Date Date0 =sdf.parse(currYear+SUFFIX_TIME_00);
Date Date1 =sdf.parse(currYear+SUFFIX_TIME_01);
Date Date2 =sdf.parse(currYear+SUFFIX_TIME_02);
Date Date3 =sdf.parse(currYear+SUFFIX_TIME_03);
if (currDate.after(Date0) && currDate.before(Date1) || currDate.equals(Date0)){
enddate=currYear+SUFFIX_TIME_04;
} else if((currDate.after(Date1) && currDate.before(Date2)) || currDate.equals(Date1) || currDate.equals(Date2)) {
enddate=(Integer.valueOf(currYear)+1)+SUFFIX_TIME_05;
} else if((currDate.after(Date2) && currDate.before(Date3)) || currDate.equals(Date3)){
enddate=(Integer.valueOf(currYear)+1)+SUFFIX_TIME_04;
}
} catch (ParseException e) { e.printStackTrace(); }
package java.util;
Date 类:before:
/**
* Tests if this date is before the specified date.
*
* @param when a date.
* @return <code>true</code> if and only if the instant of time
* represented by this <tt>Date</tt> object is strictly
* earlier than the instant represented by <tt>when</tt>;
* <code>false</code> otherwise.
* @exception NullPointerException if <code>when</code> is null.
*/
public boolean before(Date when) {
return getMillisOf(this) < getMillisOf(when);
}
Date 类:after:
/**
* Tests if this date is after the specified date.
*
* @param when a date.
* @return <code>true</code> if and only if the instant represented
* by this <tt>Date</tt> object is strictly later than the
* instant represented by <tt>when</tt>;
* <code>false</code> otherwise.
* @exception NullPointerException if <code>when</code> is null.
*/
public boolean after(Date when) {
return getMillisOf(this) > getMillisOf(when);
}
可以看出无论是before还是after,用的都是开区间判定,则在指定区间上下限时需要考虑是否将上下限本身考虑进去。此时,可能会用到equals方法去做时间等值判定,Date 类:equals:
/**
* Compares two dates for equality.
* The result is <code>true</code> if and only if the argument is
* not <code>null</code> and is a <code>Date</code> object that
* represents the same point in time, to the millisecond, as this object.
* <p>
* Thus, two <code>Date</code> objects are equal if and only if the
* <code>getTime</code> method returns the same <code>long</code>
* value for both.
*
* @param obj the object to compare with.
* @return <code>true</code> if the objects are the same;
* <code>false</code> otherwise.
* @see java.util.Date#getTime()
*/
public boolean equals(Object obj) {
return obj instanceof Date && getTime() == ((Date) obj).getTime();
}