Get the weeknumber from a given date in Java FX

强颜欢笑 提交于 2019-12-17 19:49:41

问题


I have a javafx.scene.control.DatePicker. I want to extract the (Locale) week number from the selected date. Until now i haven't found a solution and i prefer not to write my own algorithm. I use Java8 and hope it is possible in the new java time library.


回答1:


The Java-8-solution can take into account the local definition of a week using the value of a date-picker:

LocalDate date = datePicker.getValue(); // input from your date picker
Locale locale = Locale.US;
int weekOfYear = date.get(WeekFields.of(locale).weekOfWeekBasedYear());

Also keep in mind that the popular alternative Joda-Time does not support such a localized week-of-year fields. For example: In ISO-8601 (widely used) the week starts with Monday, in US with Sunday. Also the item when the first week of year starts in a given calendar year is dependent on the locale.




回答2:


You can use http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#get-java.time.temporal.TemporalField-

LocalDate localDate = LocalDate.of(2014, 9, 18); // assuming we picked 18 September 2014
int weekNumber = localDate.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);

This will give you the week number based on ISO convention.

For a locale based evaluation :

LocalDate localDate = LocalDate.of(2014, 9, 18); // assuming we picked 18 September 2014
WeekFields weekFields = WeekFields.of(Locale.US);
int weekNumber = localDate.get(weekFields.weekOfWeekBasedYear());



回答3:


FX DatePicker is based on the new (to jdk8) Date/Time api - time to learn how-to use it (not entirely sure I found the shortest way, though - corrections welcome :-)

The picker's value is a LocalDate, which can be queried for certain TemporalFields. Locale-aware week-related fields are provided by the WeekFields class, f.i. weekOfYear:

DatePicker picker = new DatePicker();
picker.valueProperty().addListener((p, oldValue, newValue) -> {
    if (newValue == null) return;
    WeekFields fields = WeekFields.of(Locale.getDefault());

    // # may range from 0 ... 54 without overlapping the boundaries of calendar year
    int week = newValue.get(fields.weekOfYear());

    // # may range from 1 ... 53 with overlapping 
    int weekBased = newValue.get(fields.weekOfWeekBasedYear());

    LOG.info("week/Based " + week + "/" + weekBased);
});

To see the difference, choose f.i. January 2012 (in locales that start a week at Monday). Which one to actually use, depends on context - the picker itself uses weekOfYear (if showWeekNumbers is enabled)




回答4:


You can also use the DateTimeFormatter, looks easier for me :

LocalDate date = LocalDate.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("w");
int week = Integer.parseInt(date.format(dtf));


来源:https://stackoverflow.com/questions/25912455/get-the-weeknumber-from-a-given-date-in-java-fx

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