获取 LocalDate 的周数 (Java 8)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26012434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Week Number of LocalDate (Java 8)
提问by YvesHendseth
I'm trying to get the Week Number of a full LocalDate with the format:
我正在尝试使用以下格式获取完整 LocalDate 的周数:
dd.MM.yyy
I haven't found a function in the Java 8 Date API wich returns the Week Number and i have tried to create a algorithm, but it did'nt work.
我还没有在 Java 8 Date API 中找到返回周数的函数,我试图创建一个算法,但它没有用。
采纳答案by Mark Rotteveel
One small warning. I haven't tested this yet, but looking at the API documentation of WeekFields
and LocalDate.get
, you should do something like:
一个小小的警告。我还没有对此进行测试,但是查看WeekFields
and的 API 文档LocalDate.get
,您应该执行以下操作:
LocalDate date = ...;
// Or use a specific locale, or configure your own rules
WeekFields weekFields = WeekFields.of(Locale.getDefault());
int weekNumber = date.get(weekFields.weekOfWeekBasedYear());
回答by Meno Hochschild
The answer of Mark Rotteveel is almost right and again an example which kind of confusion potential there is in the class WeekFields
(similar sounding method names, but deviating from intuitive civil usage). The right code requires another field:
Mark Rotteveel 的回答几乎是正确的,并且再次举例说明了课堂中存在什么样的混淆可能性WeekFields
(类似的方法名称,但偏离了直观的民间用法)。正确的代码需要另一个字段:
LocalDate date = LocalDate.now();
TemporalField woy = WeekFields.of(Locale.getDefault()).weekOfWeekBasedYear();
int weekNumber = date.get(woy);
See also the similar debate on this SO-post, especially the discussion and comments about the answer of @kleopatra.
另请参阅有关此SO-post的类似辩论,尤其是有关@kleopatra 答案的讨论和评论。