Get Week Number of LocalDate (Java 8) [duplicate]

最后都变了- 提交于 2019-12-09 07:36:02

问题


I'm trying to get the Week Number of a full LocalDate with the format:

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.


回答1:


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:

LocalDate date = ...;
// Or use a specific locale, or configure your own rules
WeekFields weekFields = WeekFields.of(Locale.getDefault()); 
int weekNumber = date.get(weekFields.weekOfWeekBasedYear());



回答2:


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:

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.



来源:https://stackoverflow.com/questions/26012434/get-week-number-of-localdate-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!