Get the weeknumber from a given date in Java FX


Question

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
5
9/18/2014 12:20:24 PM

Accepted Answer

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.

8
9/19/2014 10:03:51 AM

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());

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon