`
jianghg2010
  • 浏览: 63953 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Java 跨年周数的计算

阅读更多
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);
        }
    }

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics