package util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateFirstAndLast {
//上月最后一天
public static String getLastDayOfPreMonth(String monthDate) throws ParseException{
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
Date date = sdf1.parse(monthDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
}
//获取该月第一天
public static String getFirstDayOfMonth(String monthDate) throws ParseException{
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
Date date = sdf1.parse(monthDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
}
//获取该月最后一天
public static String getLastDayOfMonth(String monthDate) throws ParseException{
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
Date date = sdf1.parse(monthDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DATE, -1);
return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
}
//测试
public static void main(String[] args) throws ParseException {
String monthDate = "2017-04";
System.out.println("上月最后一天:"+DateFirstAndLast.getLastDayOfPreMonth(monthDate));
System.out.println("本月的第一天:"+DateFirstAndLast.getFirstDayOfMonth(monthDate));
System.out.println("本月最后一天:"+DateFirstAndLast.getLastDayOfMonth(monthDate));
}
}