1

I have following date in String.

"2022-02-01T20:32:00.000Z"

And i want to format this date to following pattern

MM/dd/yyyy HH:mm:ss a

I tried following solution from another StackOverflow question.

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate date = LocalDate.parse("2022-02-01T20:32:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); //02/01/2022

but this format gives only date and i want to time with date. so i added time format in pattern like this.

1.
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a");

2.
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a").withLocale(Locale.getDefault()).withZone(ZoneId.systemDefault());;

but it gives me following exception.

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay

So how can i achieve "MM/dd/yyyy HH:mm:ss a" pattern from "2022-02-01T20:32:00.000Z" string date?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
chiranjiv
  • 81
  • 7
  • 1
    Does this answer your question? [Format a date using the new date time API](https://stackoverflow.com/questions/23069370/format-a-date-using-the-new-date-time-api) – lorenzozane Nov 12 '20 at 09:22
  • A tip for you: paste our error message into your search engine and find the answer immediately. – Ole V.V. Nov 12 '20 at 15:02

1 Answers1

2

You can make it with two lines as this :

OffsetDateTime offset = OffsetDateTime.parse("2022-02-01T20:32:00.000Z");
String output = offset.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a"));

Output

02/01/2022 08:32:00 PM

Your string "2022-02-01T20:32:00.000Z" is formatted as the default format of OffsetDateTime, so all you need to do is to convert it to OffsetDateTime and then use another formatter to get the desired output.

As you are using a in the end of your pattern, I would suggest to use hh instead of HH.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140