How to format LocalDateTime with Timezone in Java8


In Java 8, you can format a LocalDateTime object with a timezone using the DateTimeFormatter class. Here’s an example:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeWithTimezoneExample {
    public static void main(String[] args) {
        // create a LocalDateTime object
        LocalDateTime localDateTime = LocalDateTime.now();

        // create a ZonedDateTime object using the system default timezone
        ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());

        // create a DateTimeFormatter object with the desired format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");

        // format the ZonedDateTime object with the formatter
        String formattedDateTime = zonedDateTime.format(formatter);

        // print the formatted datetime string
        System.out.println(formattedDateTime);
    }
}

This will output a string in the format of yyyy-MM-dd HH:mm:ss z, where z represents the timezone abbreviation. You can replace the ZoneId.systemDefault() with a specific timezone if you want to format the LocalDateTime object with a different timezone.