Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the weeknumber from a given date in Java FX

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.

like image 831
Hans Avatar asked Sep 18 '14 12:09

Hans


2 Answers

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.

like image 141
Meno Hochschild Avatar answered Sep 20 '22 07:09

Meno Hochschild


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());
like image 38
bowmore Avatar answered Sep 22 '22 07:09

bowmore