Home > Software design >  How to convert a LocalDateTime date to a particular format?
How to convert a LocalDateTime date to a particular format?

Time:10-27

Hi I am having small Java code snippet. I am using Java 8. I have a Java LocalDateTime object and I want to format it. Please see my code below.

String dateUTC = "2021-10-21T10:32:38Z";
Instant i =  Instant.parse(dateUTC);
LocalDateTime ldt = i.atZone(ZoneId.of("Europe/London")).toLocalDateTime();

I want to print the LocalDateTime object ldt as string in the following format:

 Oct 21 2021 11:32:38 AM

How can I achieve that?

CodePudding user response:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm:ss a");  
System.out.println(  ldt.format(dateTimeFormatter));

CodePudding user response:

Use a built-in localized format

Can you live with commas in the output?

    DateTimeFormatter dateTimeFormatter
            = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
                    .withLocale(Locale.US);  
    System.out.println(ldt.format(dateTimeFormatter));

Output:

Oct 21, 2021, 11:32:38 AM

The immediate advantage is that we don’t need to fiddle with any format pattern string, which is always an error-prone task. Two further advantages are: 1. users likely will be happier with the built-in format since this is constructed to fit the expectations of the people in the locale (USA in the example); 2. the code trivially lends itself well to localization: just specify a different locale to make people of a different culture happy.

  • Related