java 1.6.0 22,Java日历问题,JDK 1.6.0.22

I have a problem with getting the week of year. On my machine JDK 1.6.0.22 version is installed, on another machine 1.6.0.21. And both machines return different results:

(1.6.0.22) week is: 1

(1.6.0.21) week is: 52

For this code:

try {

Calendar current = new GregorianCalendar();

DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

Date d = df.parse("2010-12-28 19:04:38 GMT");

current.setTime(d);

int currentWeek = current.get(Calendar.WEEK_OF_YEAR);

System.out.println("week is: "currentWeek);

} catch (ParseException e) {

e.printStackTrace();

}

Why does JDK 1.6.0.22 give the wrong result?

解决方案

This excerpt from the API documentation explains why this difference can occur:

Values calculated for the WEEK_OF_YEAR

field range from 1 to 53. Week 1 for a

year is the earliest seven day period

starting on getFirstDayOfWeek() that

contains at least

getMinimalDaysInFirstWeek() days from

that year. It thus depends on the

values of getMinimalDaysInFirstWeek(),

getFirstDayOfWeek(), and the day of

the week of January 1.

And from the source code of Calendar:

Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.

So it's the locale that determines this, not the time zone! Apparently, in some locales, week 1 of a year is considered to begin in the previous year. Try running this:

Calendar cal = new GregorianCalendar();

System.out.println(Locale.getDefault());

System.out.println(cal.getMinimalDaysInFirstWeek());

System.out.println(cal.getFirstDayOfWeek());

I bet that either you're running the different versions in different locales, or the locale data changed between these versions. The result "1" could even be the more correct one and due to a bug fix in the locale data.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值