gpt4 book ai didi

windows - Java日历问题,JDK 1.6.0.22

转载 作者:可可西里 更新时间:2023-11-01 13:51:35 26 4
gpt4 key购买 nike

我在获取一年中的星期几时遇到问题。在我的机器上安装了JDK 1.6.0.22版本,在另一台机器上安装了1.6.0.21。两台机器返回不同的结果:

(1.6.0.22) week is: 1
(1.6.0.21) week is: 52

对于这段代码:

      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();
}

为什么 JDK 1.6.0.22 会给出错误的结果?

最佳答案

本节摘录from the API documentation解释为什么会出现这种差异:

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.

并且来自Calendar的源代码:

Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.

因此决定这一点的是区域设置,而不是时区!显然,在某些区域设置中,一年的第 1 周被认为是从前一年开始的。尝试运行这个:

    Calendar cal = new GregorianCalendar();
System.out.println(Locale.getDefault());
System.out.println(cal.getMinimalDaysInFirstWeek());
System.out.println(cal.getFirstDayOfWeek());

我敢打赌,要么您在不同的语言环境中运行不同的版本,要么这些版本之间的语言环境数据发生了变化。由于语言环境数据中的错误修复,结果“1”甚至可能是更正确的结果。

关于windows - Java日历问题,JDK 1.6.0.22,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4549027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com