根據指定日期擷取上一個月
看過不少類似文章,根據一個日期,要取得相應的上一個月的值,則利用Calendar的api:get(Calendar.MONTH) - 1)來算。
思路是對的,但這個api有坑的,例如:目前日期為:2021-03-30,得到的上一月的結果為:202103,但我們期望結果是:202102。
因為Calendar計算時,如果有時間算時間、有天算天,但我們期望結果是得到月,是以要先確定目前日期精确到月,即換算機關相同,具體代碼如下,請參考:
DateUtil.YYYYMM常量,即字元串:"yyyyMM"
/**
* 根據指定的日期對象,傳回上一個年月字元串
* @param theDate 指定的日期對象
* @return
*/
public static String getLastYearMonth(Date theDate) {
Calendar now = Calendar.getInstance();
String yearMonth;
if (theDate == null) {
yearMonth = DateUtil.format(now.getTime(), DateUtil.YYYYMM);
theDate = DateUtil.convert(yearMonth, DateUtil.YYYYMM);
} else {
yearMonth = DateUtil.format(theDate, DateUtil.YYYYMM);
}
theDate = DateUtil.convert(yearMonth, DateUtil.YYYYMM);
now.setTime(theDate);
now.set(Calendar.MONTH, now.get(Calendar.MONTH) - 1);
return DateUtil.format(now.getTime(), DateUtil.YYYYMM);
}
Good luck!