System.out.println(
DateTimeFormatter.ofPattern("YYYY-ww").withZone(ZoneOffset.UTC).format(Instant.parse("2022-05-10T00:00:00.00Z"))
);
System.out.println(
DateTimeFormatter.ofPattern("YYYY-ww").withZone(ZoneOffset.UTC).format(Instant.parse("2022-05-17T00:00:00.00Z"))
);为什么这种模式YYYY-ww在Ubuntu和Mac上的解析方式不同:
Ubuntu:(默认地区en_US,我的计算机)
2022-20
2022-21Mac: (默认区域设置en_GB)
2022-19
2022-20编辑
System.out.println(
DateTimeFormatter.ofPattern("YYYY-ww").withLocale(Locale.UK).withZone(ZoneOffset.UTC).format(Instant.parse("2022-05-10T00:00:00.00Z"))
);
System.out.println(
DateTimeFormatter.ofPattern("YYYY-ww").withLocale(Locale.UK).withZone(ZoneOffset.UTC).format(Instant.parse("2022-05-17T00:00:00.00Z"))
);返回:
2022-19
2022-20 尽管如此,问题是为什么模式ww是特定于地区的?我在https://docs.oracle.com/javase/8/docs/api/java/time/temporal/WeekFields.html或https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html的文档中没有看到这一点
发布于 2022-05-30 14:30:11
在美国,一年的第一周可以有一到七天,而在英国,一年的第一周至少需要4天。
WeekFields.of(Locale.UK).getMinimalDaysInFirstWeek() // 4
WeekFields.of(Locale.US).getMinimalDaysInFirstWeek() // 1此外,美国周从周日开始,而英国周从周一开始。
这意味着对美国来说,2022年的第一周是2022-01-01的一个星期六,2022-01-02是第二周的开始。另一方面,对于英国来说,2022年的第一周从2022-01-03开始,因为一年的头两天没有形成一周。这就是美国机器增加一周的原因。
在使用DateTimeFormatter创建ofPattern时,将使用机器的默认格式化区域设置:
格式化程序将使用默认格式区域设置。这可以在返回的格式化程序上使用
withLocale(Locale)进行更改。
这就是区别所在。
我想您在这里需要标准的ISO 8601周,而不希望与区域设置有任何关系。这样做的一种方法是使用DateTimeFormatter构造IsoFields
var dtf = new DateTimeFormatterBuilder()
. appendValue(IsoFields.WEEK_BASED_YEAR, 4)
.appendLiteral('-')
.appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 2)
.toFormatter().withZone(ZoneOffset.UTC);
System.out.println(
dtf.format(Instant.parse("2022-05-10T00:00:00.00Z"))
);
System.out.println(
dtf.format(Instant.parse("2022-05-17T00:00:00.00Z"))
);发布于 2022-05-30 18:16:48
“周”的定义因地区而异
清道夫的回答是正确的。一周有几个定义,它们因地区而异。
你问:
然而,问题是为什么ww模式是特定于地区的?
因为周的定义是文化的。
甚至把我们的范围限制在西方目前常见的七天一周内,哪一天是一周的第一天?星期一在欧洲很常见,而美国则在周日使用。第一周应该从一周的第一天开始吗?还是从1月1日开始一周?
ISO 8601标准
如果要保持一致性,请考虑使用标准的ISO 8601周定义:
标准格式是四位数的年份、连字符、W和两位数的周数.标准格式的设计巧妙,避免了模棱两可,易于被机器解析,并为跨文化的人类所理解。
要使用ISO8601周,我建议将https://www.threeten.org/threeten-extra/库添加到您的项目中,用于其YearWeek类。
YearWeek yw = YearWeek.parse( "2022-W19" ) ;
String output = yw.toString() ;按日期计算一年一周。
LocalDate ld = LocalDate.parse( "2022-05-10" ) ;
YearWeek yw = YearWeek.from( ld ) ;从以标准ISO 8601格式表示的文本所表示的UTC时刻起,获得一年一周的时间.下面看到的Z意味着与UTC的零小时-分-秒的偏移,并且发音为“祖鲁”。
String input = "2022-05-10T00:00:00.00Z" ;
Instant instant = Instant.parse( input ) ;
OffsetDateTime odt = instant.at( ZoneOffset.UTC ) ;
YearWeek yw = YearWeek.from( odt ) ; https://stackoverflow.com/questions/72435074
复制相似问题