传参2022-02
/**
* 获取2022-03 过去一个月和过去一年的时间 并返回 2022-03 格式
* @param month 需要修改的时间
* @return 返回 beforeMonth 过去一个月 beforeYear 过去一年的时间
*/
@SneakyThrows
public Map getbeFore(String month){
//定义转化的时间格式
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat ym=new SimpleDateFormat("yyyy-MM");
Date date=null;
try {
//加上15好以计算下个月
date=sdf.parse(month+"-15");
System.out.println(date);
//打印结果:Tue Feb 15 00:00:00 GMT+08:00 2022
} catch (ParseException e) {
e.printStackTrace();
throw new Exception("转换时间有误");
}
//计算过去的一个月即减去一个月的结果
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH,-1);
String beforeMonth =ym.format(calendar.getTime());
//计算过去的一年即减去一个年的结果
Calendar calendar1=Calendar.getInstance();
calendar1.setTime(date);
calendar1.add(Calendar.YEAR,-1);
String beforeYear =ym.format(calendar1.getTime());
//减去一个月
System.out.println("beforeMonth:"+beforeMonth);
//减去一年
System.out.println("beforeYear:"+beforeYear);
//进入map格式,返回
Map<String,String> beforeTime=new HashMap<>();
beforeTime.put("beforeMonth",beforeMonth);
beforeTime.put("beforeYear",beforeYear);
return beforeTime;
}
打印及结果
Tue Feb 15 00:00:00 GMT+08:00 2022
beforeMonth:2022-01-15
beforeYear:2021-02-15
希望可以帮助你们解决问题,返回的格式可以自由更改