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 ?

0

1 Answer 1

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

1
  • 1
    Thanks Murilo...You are Super. Worked like a charm.
    – RohitT
    Commented Aug 22, 2020 at 15:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.