-1

I am trying to parse the date in a specific pattern but every time it is showing date in only format. Here what I am doing. Output is written in comments in front of the line.

String dat = "20-06-2021";

String newFormatLocaleDate = "MMM dd yyyy";
String newFormattedDate = convertToNewFormat(dat,currentFormat,newFormatLocaleDate); //Jun 20 2021
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern(newFormatLocaleDate);
LocalDate parse1 = java.time.LocalDate.parse(newFormattedDate,formatter1); //2021-06-20
System.out.println("Using parse1 Pattern Only "+parse1);  //2021-06-20
Date date1 = java.sql.Date.valueOf(parse1);
System.out.println("Using Date Pattern Only "+date1);  //2021-06-20

The pattern in which date is required is given and in the string form it giving the correct value but when I am trying to parse it with LocaleDate it is changing the format for all dates to the above mentioned (yyyy-MM-dd) format irrespective of the newFormatLocaleDate pattern.

Thanks

Gregor Zurowski
  • 2,222
  • 2
  • 9
  • 15
nee nee
  • 79
  • 4
  • 2
    What does `convertToNewFormat` do? – Sweeper Jun 23 '21 at 11:41
  • it will take the date which needs to be converted to new format , the current format of the date, the new format of the date in which it is required to be converted . It is working fine and working as per the need. – nee nee Jun 23 '21 at 11:44
  • 1
    "It is working fine and working as per the need" doesn't mean you don't have to post it here. You need a [mcve]. Anyway, it's unclear what the problem is. If you want `MMM dd yyyy` format, can't you just use `newFormattedDate`? Why parse it to another `LocalDate`? – Sweeper Jun 23 '21 at 11:49
  • 1
    The line `System.out.println("Using parse1 Pattern Only " + parse1);` will implicitly use `parse1.toString()` which has a fixed (ISO) format. You could define your output format by `parse1.format(formatter1, Locale.ENGLISH);`. – deHaar Jun 23 '21 at 11:55

2 Answers2

4

You should not expect the line

System.out.println("Using parse1 Pattern Only "+parse1);

to output something different than 2021-06-20 it literally is exactly what the docs say what will be out putted.

The output will be in the ISO-8601 format uuuu-MM-dd.

So regardless of the format you used while parsing the LocalDate value the toString method will always output a data in the format uuuu-MM-dd.

If you want a different format use the instance method format.

Ackdari
  • 3,222
  • 1
  • 16
  • 33
1

Please note that you are printing the LocalDate and Date instances (using their toString() implementation), therefore not formatted according to your desired template. If you want to print out your parsed date in a particular format, you need to apply a formatter again, for example like this:

System.out.println(parse1.format(DateTimeFormatter.ofPattern("MMM dd yyyy")))
Gregor Zurowski
  • 2,222
  • 2
  • 9
  • 15