Home > OS >  Convert date format in springboot using java8
Convert date format in springboot using java8

Time:04-29

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

CodePudding user response:

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);

CodePudding user response:

Almost the same answer is already given. The given input format looks like Date.toSTring(), especially as weekday and month seem to be English, but might be German too. Below with Locale.ENGLISH (as suggested by "CET") but Locale.GERMAN might be better.

    String newDate = "Mon Apr 25 04:50:00 CET 2022";
    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern("eee MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    ZonedDateTime t = ZonedDateTime.parse(newDate, formatter);
    System.out.println(t);
    System.out.println(Date.from(t.toInstant()));
    System.out.println(t.format(DateTimeFormatter.ISO_DATE_TIME));
    System.out.println(t.toLocalDateTime().format(DateTimeFormatter.ISO_DATE_TIME));
    System.out.println(t.withZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime()
        .format(DateTimeFormatter.ISO_DATE_TIME));

The output variants are:

Mon Apr 25 04:50:00 CEST 2022
2022-04-25T04:50 02:00[Europe/Paris]
2022-04-25T04:50:00 02:00[Europe/Paris]
2022-04-25T04:50:00
2022-04-25T02:50:00

It is indeed best to start with a ZonedDateTime.

If you get input all over Europe, it would be best to use Universal Time Coordinated, Greenwich time. (But it often depends on the existing database data.)

  • Related