JAVA 取上个月、当月第一天、当月最后一天

/**取上个月*/
public void test1(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar calendar = Calendar.getInstance();
		Date curDate = java.sql.Date.valueOf("2012-12-22");
		calendar.setTime(curDate);
		//取得现在时间
		System.out.println(sdf.format(curDate));

		//取得上一个时间
		calendar.set(Calendar.MONDAY, calendar.get(Calendar.MONDAY) - 1);

		//取得上一个月的下一天
		calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
		System.out.println(sdf.format(calendar.getTime()));

}

/**取本月第一天或最后一天*/
public void test2(){
Calendar cal = Calendar.getInstance(); 
  cal.setTime(new Date()); 
  cal.set(Calendar.DAY_OF_MONTH, 1); 
  System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime())); 
  cal.roll(Calendar.DAY_OF_MONTH, -1);  
  System.out.println (new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
}

你可能感兴趣的:(java)