Get the weeknumber from a given date in Java FX

前端 未结 4 880
孤城傲影
孤城傲影 2020-12-11 04:46

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

4条回答
  •  独厮守ぢ
    2020-12-11 05:25

    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)

提交回复
热议问题