Skip to content
Advertisement

Java DateTime output formatter equivalent to Calender.getInstance method

I am trying to replace old java Date with new DateTime. I am running the below code to check various formats:

public class MyMain {

    public static void main(String[] args) {
        Date date     = new Date();
        Date calender = Calendar.getInstance().getTime();
        LocalDate ld  = LocalDate.now();
        LocalTime lt  = LocalTime.now();
        LocalDateTime ldt = LocalDateTime.now();
        ZonedDateTime zdt = ZonedDateTime.now();

        DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
        
        System.out.println("Date          :: " +date);
        System.out.println("Calender      :: " +calender);
        System.out.println("LocalDate     :: " +ld);
        System.out.println("LocalTime     :: " +lt);
        System.out.println("LocalDateTime :: " +ldt);       
        System.out.println("ZonedDateTime :: " +dtf.format(zdt));
        
    }
}

This is the output I got :

Date          :: Fri Aug 27 13:21:29 IST 2021
Calender      :: Fri Aug 27 13:21:29 IST 2021
LocalDate     :: 2021-08-27
LocalTime     :: 13:21:29.449
LocalDateTime :: 2021-08-27T13:21:29.449
ZonedDateTime :: Friday, 27 August, 2021 1:21:29 PM IST

I want to format the output for LocalDateTime/ZonedDateTime in such a way that it is equivalent to the Calender output. But I am unable to achieve that. Can someone help.

This is what I wish to get the output as : Fri Aug 27 13:21:29 IST 2021

Advertisement

Answer

You need to define a pattern for this specific output:

public static void main(String[] args) throws Exception {
    // take the current moment in time in the desired zone
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
    // then print a formatted String
    System.out.println(now.format(
            DateTimeFormatter.ofPattern("EEE, MMM dd HH:mm:ss z uuuu",
                                        Locale.ENGLISH)
        )
    );
}

Defining the zone explicitly is probably not necessary on your system since it has the desired zone (mine one is different, so I had to do it).

However, the output of this was (some moments ago):

Fri, Aug 27 13:38:22 IST 2021
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement