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
*/
public static String getPastDate(int past, String time, Integer type) {
//改为以- 截取 防止出现 不是标准时间格式
LocalDate now = LocalDate.now();
int index = time.indexOf("-");
Integer month =0;
int indexOf=0;
if(time.length()>7){
indexOf = time.indexOf("-", index + 1);
month = Integer.valueOf(time.substring(index + 1, indexOf));
}else {
String str=time.substring(0, time.indexOf("-"));
String bb=time.substring(str.length()+1, time.length());
month = Integer.valueOf(bb);
}
Integer year = Integer.valueOf(time.substring(0, time.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();
}