SimpleDateFormat sdftest = new SimpleDateFormat("yyyy-MM-dd");
Date stfDate = sdftest.parse("2021-12-20");
String dateTest1 = getYearOrMonthByDate(stfDate,1);
type为1,则获取年,为2,则获取月
/**
* 根据指定日期格式返回年或月
*
* @return date
*/
public static String getYearOrMonthByDate(Date date, Integer type) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date stfDate = date;
Calendar cal = Calendar.getInstance();
cal.setTime(stfDate);
Integer month = cal.get(Calendar.MONTH)+1;
Integer result = null;
String resultStr = "";
if(type.equals(1)){
result = cal.get(Calendar.YEAR);
resultStr = result.toString();
}else if(type.equals(2)){
result = cal.get(Calendar.MONTH)+1;
if(result<10){
resultStr = "0"+result.toString();
}else {
resultStr = result.toString();
}
}
return resultStr;
}