I am giving you Java code trusting that you can translate to Scala:
LocalDate date = LocalDate.parse("20180312", DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(date);
Output:
2018-03-12
No need for the notoriously troublesome SimpleDateFormat
class and its long outdated friends Calendar
and Date
. No need to specify a format pattern string yourself since the formatter you need is built-in. No way to get the case of format pattern letters wrong. java.time, the modern Java date and time API is giving you all this. I warmly recommend it. On top of this, the LocalDate
class of java.time matches your need much more precisely than Date
or Calendar
: a LocalDate
is a date without time-of-day.
What went wrong in your code?
Uppercase YYYY
in the format pattern string is for week-based year, the year that the week number of the week belongs to (so really only useful with week numbers). MM
is fine for month. Uppercase DD
is for the number of the day within the year (lowercase dd
is for day of month). So you asked for the week-based year that began with week 1 of 2018, month of March and the 12th day of the year. This is self-contradictory. One of the troublesome traits of SimpleDateFormat
is that where it ought to throw an exception with such impossible requirements, instead it pretends that all is well and gives you some incorrect result. Let me guess, your week begins on Sunday? So apparently it gave up on month and day-of-year (since it didn’t really know the calendar year) and just gave you the first day of week 1. On my computer I got Mon Jan 01 00:00:00 CET 2018, which probably is because Monday is the first day of the week here.
Link
Oracle tutorial: Date Time explaining how to use java.time
.