Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse week strings for comparison using Java 8

I want to compare string representations of weeks, e.g. week "01/17" is before "02/17" and after "52/16".

The following code throws an exception, I guess because my string doesn't hint at the exact day of each week. However, I don't care - it could all be Mondays or Thursdays or whatever:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ww/YY", Locale.GERMANY);
LocalDate date1 = formatter.parse(str1, LocalDate::from);

Do I need to modify the parser? Or parse to some other format? Unfortunatley there is no object like YearMonth for weeks...

like image 490
Tom Avatar asked May 11 '26 21:05

Tom


2 Answers

One solution would be to always default to the same day, say the Monday. You could build a custom formatter for that:

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
          .appendPattern("ww/YY")
          .parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
          .toFormatter(Locale.GERMANY);

You can now build LocalDates representing the Monday of the given week:

LocalDate d1 = LocalDate.parse("01/17", fmt);
LocalDate d2 = LocalDate.parse("52/16", fmt);
System.out.println(d1.isAfter(d2));

which prints true because 01/17 is after 52/16.

like image 187
assylias Avatar answered May 14 '26 17:05

assylias


I wasn't able to find a way for this to work with the DateTimeFormatter class, but I would like to suggest a different approach.

The Threeten Extra library contains a number of classes that were deemed too specific to include in the java.time library. One of them is the YearWeek class you mention.

Your problem can be solved by parsing the week-number and year manually from the input-string and then invoking the YearWeek creator-method like this:

YearWeek yw = YearWeek.of(year, monthOfYear);
like image 34
Henrik Aasted Sørensen Avatar answered May 14 '26 18:05

Henrik Aasted Sørensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!