java.time
looking for java.time.* solution which can parse yyyyddd format
That’s what I recommend too.
DateTimeFormatter dayOfYearFormatter
= DateTimeFormatter.ofPattern("uuuuDDD");
DateTimeFormatter yearMonthFormatter
= DateTimeFormatter.ofPattern("uuMM");
String yyyydddString = "2020366";
LocalDate date = LocalDate.parse(yyyydddString, dayOfYearFormatter);
String output = date.format(yearMonthFormatter);
System.out.println(output);
Output is:
2012
So year 2020 month 12.
What went wrong in your code?
Whether you use the modern DateTimeFormatter
or the old and troublesome SimpleDateFormat
, lowercase d
is for day of month and uppercase D
is for day of year. Why it worked with SimpleDateFormat
anyway was because that class confusingly defaults month to January if no month is given. So your date was parsed into the 366th day of January. What?! That’s right, one more confusing trait of SimpleDateFormat
, with default settings it happily parses non-existent dates. When there are only 31 days in January, it just extrapolates into the following months and ends up at December 31, the day you had intended. SimpleDateFormat
is so full of nasty surprises like these. I recommend you never ever use that class again.
Link
Oracle tutorial: Date Time explaining how to use java.time.