javascalajava-timelocaldatedatetimeformatter

How to convert weeks of year to LocalDate


I have a string with both year-week e.g. "2015-40" and year-month formats e.g. "2015-08", that would like to transform into LocalDate in Scala.

I have tried using

val date = "2015-40"
val formatter = DateTimeFormatter.ofPattern("yyyy-ww") 
LocalDate.parse(date, formatter)

but end up with DateTimeParseException error. Would appreciate any help on how to do this

Thanks in advance


Solution

  •     String date = "2015-40";
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendPattern("YYYY-ww")
                .parseDefaulting(ChronoField.DAY_OF_WEEK, DayOfWeek.MONDAY.getValue())
                .toFormatter(Locale.FRANCE);
        LocalDate ld = LocalDate.parse(date, formatter);
        
        System.out.println(ld);
    

    Sorry that I can write only Java, I trust you to translate to Scala. Output is:

    2015-09-28

    Why were you getting an exception? There were a couple of things missing for us to parse 2015-40 into a LocalDate:

    As an aside, if you can influence the format, consider 2015-W40 with a W. This is ISO 8601 format for year and week. In ISO 2015-12 denotes year and month, and many will read it this way. So to disambiguate and avoid misreading.

    Edit:

    In my explanation I have assumed ISO week scheme (Monday is the first day of week and week 1 is defined as the first week having at least 4 days in the new year). You may pass a different locale to the formatter builder to obtain a different week scheme.

    If you are sure that your weeks follow ISO, Andreas’ suggestion in the comment is good enough that we want as part of the answer:

    Alternatively, add the ThreeTen Extra library, so you can use the YearWeek class, that has a nice atDay​(DayOfWeek dayOfWeek) method for getting a LocalDate.

    Link: Wikipedia article: ISO 8601