SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd , ww, E");
//sdf.format("2009-12-31");
Calendar cl = Calendar.getInstance();
cl.setFirstDayOfWeek(GregorianCalendar.SUNDAY);// 每周以周日开始
cl.setMinimalDaysInFirstWeek(3); // 每年的第一周必须大于或等于3天,否则就算上一年的最后一周
// cl.set(2009, 11, 26); // 使用SimpleDateFormat获取的周数是错误的,get(Calendar.WEEK_OF_YEAR)是对的
// System.out.println(sdf.format(cl.getTime())+"/t"+cl.get(Calendar.WEEK_OF_YEAR)+"/t"+getYearOfWeek(cl));
// cl.set(2009, 11, 27);
// System.out.println(sdf.format(cl.getTime())+"/t"+cl.get(Calendar.WEEK_OF_YEAR)+"/t"+getYearOfWeek(cl));
// cl.set(2010, 0, 1);
// System.out.println(sdf.format(cl.getTime())+"/t"+cl.get(Calendar.WEEK_OF_YEAR)+"/t"+getYearOfWeek(cl));
// cl.set(2010, 0, 2);
// System.out.println(sdf.format(cl.getTime())+"/t"+cl.get(Calendar.WEEK_OF_YEAR)+"/t"+getYearOfWeek(cl));
sdf = new SimpleDateFormat("yyyy-MM-dd");
cl.set(2010,4-1,25); // 2010-04-25
System.out.println(sdf.format(cl.getTime())+" 属于第"+cl.get(Calendar.WEEK_OF_YEAR)+"周");
cl.set(Calendar.DAY_OF_WEEK,GregorianCalendar.SUNDAY);
System.out.println("第"+cl.get(Calendar.WEEK_OF_YEAR)+"周第1天:"+sdf.format(cl.getTime()));
cl.roll(Calendar.DAY_OF_WEEK,-1);
System.out.println("第"+cl.get(Calendar.WEEK_OF_YEAR)+"周第7天:"+sdf.format(cl.getTime()));
cl.set(2010,4-1,25);
cl.add(Calendar.WEEK_OF_YEAR, -1);
System.out.println(sdf.format(cl.getTime())+" 属于第"+cl.get(Calendar.WEEK_OF_YEAR)+"周");
cl.set(Calendar.DAY_OF_WEEK,GregorianCalendar.SUNDAY);
System.out.println("第"+cl.get(Calendar.WEEK_OF_YEAR)+"周第1天:"+sdf.format(cl.getTime()));
cl.roll(Calendar.DAY_OF_WEEK,-1);
System.out.println("第"+cl.get(Calendar.WEEK_OF_YEAR)+"周第7天:"+sdf.format(cl.getTime()));
System.out.println("==================");
cl.set(2010,4-1,25); // 2010-04-25
System.out.println(sdf.format(cl.getTime())+" 属于第"+(cl.get(Calendar.MONTH)+1)+"月");
cl.set(Calendar.DAY_OF_MONTH, 1);
System.out.println(sdf.format(cl.getTime()));
cl.roll(Calendar.DAY_OF_MONTH, -1);
System.out.println(sdf.format(cl.getTime()));
cl.set(2010,4-1,25); // 2010-04-25
cl.add(Calendar.MONTH, -1);
System.out.println(sdf.format(cl.getTime())+" 属于第"+(cl.get(Calendar.MONTH)+1)+"月");
cl.set(Calendar.DAY_OF_MONTH, 1);
System.out.println(sdf.format(cl.getTime()));
cl.roll(Calendar.DAY_OF_MONTH, -1);
System.out.println(sdf.format(cl.getTime()));
计算周、月的开始与结束日期
最新推荐文章于 2021-04-04 02:14:03 发布