public static String getStartDate(String date){
String resultString;
try {
if(StringUtils.isEmpty(date)){
return getEndDate();
}
Calendar cal = Calendar.getInstance();
java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
cal.add(Calendar.MONTH, -1);
int day = Integer.parseInt(StringUtils.substring(date, StringUtils.lastIndexOf(date, "-") + 1, date.length()));
cal.set(Calendar.DATE, day);
String lastMonthStart = format.format(cal.getTime());//上月开始
cal.clear();
resultString = lastMonthStart;
} catch (NumberFormatException e) {
return getEndDate();
}
return resultString;
}
private static String getEndDate(){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
return df.format(new Date());// new Date()为获取当前系统时间
}
public static void main(String[] args){
String endDate = getEndDate();
String startDate = getStartDate(endDate);
System.out.println("start=" + startDate);
System.out.println("end=" + endDate);
}
输出:
start=2012-11-20
end=2012-12-20