import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class WeekOfYear {
/**
* @param args
*/
public static void main(String[] args) {
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"+getWeekOfYear(cl));
cl.set(2009, 11, 27);
System.out.println(sdf.format(cl.getTime())+"/t"+cl.get(Calendar.WEEK_OF_YEAR)+"/t"+getWeekOfYear(cl));
cl.set(2010, 0, 1);
System.out.println(sdf.format(cl.getTime())+"/t"+cl.get(Calendar.WEEK_OF_YEAR)+"/t"+getWeekOfYear(cl));
cl.set(2011, 0, 2);
System.out.println(sdf.format(cl.getTime())+"/t"+cl.get(Calendar.WEEK_OF_YEAR)+"/t"+getWeekOfYear(cl));
}
// 但前日期所在的周属于上一年或是下一年。13017614465
public static int getWeekOfYear(Calendar cl){
if(cl.get(Calendar.MONTH)==Calendar.JANUARY && cl.get(Calendar.WEEK_OF_YEAR)>50){
return cl.get(Calendar.YEAR)-1;
}else{
return cl.get(Calendar.YEAR);
}
}
}
Java 跨年周数的计算
最新推荐文章于 2023-08-02 14:52:15 发布