import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CalendarUtil2 {

	public static void main(String[] args) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
	 
		SimpleDateFormat ff = new SimpleDateFormat("M/yyyy");
		ff.applyPattern("yyyy-MM-dd HH:mm:ss");
		int firstDayOfWeek = Calendar.MONDAY;//周一
		
		for (int i = 0; i < 12; i++) {
			calendar.add(Calendar.MONTH, -1);
	        
	        int weekFirst = calendar.getFirstDayOfWeek();
	        System.out.println("firstDD:"+weekFirst);
	        //设置为最后一天
	        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); 
	        System.out.println("当前月份最后一天:"+ff.format(calendar.getTime()));
	        
	        int month = calendar.get(Calendar.MONTH);//当月
		//可以指定一周内的其他天
	        //calendar.setFirstDayOfWeek(firstDayOfWeek);
	        System.out.println("firstDD:"+calendar.getFirstDayOfWeek());
	        //最近这一周的起始日期【将DAY_OF_WEEK设置为周的第一天,则日期也会发生变化,变为对应天数】
	        calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
	        
	        Date current = calendar.getTime();
	        //判断是否超过本月
	        calendar.add(calendar.DATE, 6);
	        int weekMonth = calendar.get(Calendar.MONTH);//加了一周后的月份
	        if(weekMonth==month){//刚好是最后一周
	        	System.out.println("startTime:"+ff.format(current));
	        	System.out.println("endTime:"+ff.format(calendar.getTime()));
	        }else{//向前取一天作为结束时间,再向前取六天作为开始
	        	calendar.add(Calendar.DATE, -6-1);
	        	String endTime = ff.format(calendar.getTime());
	        	calendar.add(Calendar.DATE, -6);
	        	String startTime = ff.format(calendar.getTime());
	        	System.out.println("startTime:"+startTime);
	        	System.out.println("endTime:"+endTime);
	        }
	        System.out.println("=========================================");
		}
        
	}
 
}

  

 

参考资料:

https://teakki.com/p/59021ad8b819c55a2789c8af

 posted on 2017-11-27 18:56  a12345531  阅读(936)  评论(0编辑  收藏  举报