指定日期的前後幾天的日期或者月份
阿新 • • 發佈:2021-06-22
1
public static String asd(int past, String time, Integer type) { //time yyyy-MM-dd LocalDate now = LocalDate.now(); Integer year = Integer.valueOf(time.substring(0, 4)); Integer month = Integer.valueOf(time.substring(5, 7)); if (type == 1) { //天 Integer day = Integer.valueOf(time.substring(8, 10)); LocalDate localDate= LocalDate.of(year, month, day); LocalDate localTimeDay = localDate.minusDays(past); return localTimeDay.toString(); } else if (type == 2) { Integer day = 01; //月 LocalDate localDate = LocalDate.of(year, month, day); LocalDate localTimeMonth= localDate.minusMonths(past); return localTimeMonth.toString().substring(0, 7); } return now.toString(); }
但是這種也不算是很完美 按照下標擷取還是很不保險 ,測試的時候就發現 有人傳 2021-6-2 這種不是標準格式的。
所以有第二種方式。
2
/** * 獲取指定日期的前幾天或月份的日期 * * @param past * @return */ publicstatic String getPastDate(int past, String time, Integer type) { //改為以- 擷取 防止出現 2021-6-2 LocalDate now = LocalDate.now(); int index = time.indexOf("-"); int indexOf = time.indexOf("-", index + 1); Integer year = Integer.valueOf(time.substring(0, time.indexOf("-"))); Integer month = Integer.valueOf(time.substring(index + 1, indexOf)); if (type == 1) { //天 Integer day = Integer.valueOf(time.substring(indexOf + 1)); LocalDate localDate = LocalDate.of(year, month, day); LocalDate localTimeDay = localDate.minusDays(past); return localTimeDay.toString(); } else if (type == 2) { Integer day = 01; //月 LocalDate localDate = LocalDate.of(year, month, day); LocalDate localTimeMonth = localDate.minusMonths(past); return localTimeMonth.toString().substring(0, 7); } return now.toString(); }