1

I want to convert Date to String in different formats, but i am getting the below error,

DateTimeException-Field DayOfYear cannot be printed as the value 234 exceeds the maximum print width of 2

Below are the different formats,

"MMDDYY"
"DD_MM_YY" 
"YYYYMMDD"
"MMDD"
"DD-MM-YY"

Below is my code,

LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("DD-MM-YY");
String formattToString = localDate.format(formatter);

Am i missing something here ?

RohitT
  • 187
  • 2
  • 11

1 Answers1

6

DD (uppercase) means DD - day-of-year, in this case is printing 234, so you have to replace to dd (lowercase), that will work fine. YY is not causing the error in your case, but change It to yyyy. Try to change your code like it:

LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattToString = localDate.format(formatter);

This tutorial has some Pattern Examples: http://tutorials.jenkov.com/java-internationalization/simpledateformat.html

Murilo Góes de Almeida
  • 1,588
  • 5
  • 20
  • 42