Skip to content
Advertisement

Convert date format in springboot using java8

I receive the following date format

private String newDate = "Mon Apr 25 04:50:00 CET 2022"

How can I convert it into the following format in java 8

2022-04-25T04:50:00

Advertisement

Answer

You can use Java 8’s date/time API, and more precisely the DateTimeFormatter.

There’s no pre-defined formatter that matches your initial input. The closest is DateTimeFormatter.RFC_1123_DATE_TIME, but it requires a comma after the day of the week.

To solve that, you can write your own pattern:

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.ROOT));
String input = "Mon Apr 25 04:50:00 CET 2022";
ZonedDateTime date = ZonedDateTime.parse(input, inputFormatter);

The best way to represent your initial date is a ZonedDateTime, since your date contains zone-related information.

For your output, you can use the DateTimeFormatter.ISO_LOCAL_DATE_TIME formatter. For example:

String output = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(date);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement