Java Convert ZonedDateTime to String Example

ZonedDateTime class provides below APIs to convert or format ZonedDateTime to String in Java.
  • String format(DateTimeFormatter formatter) - Formats this date-time using the specified formatter.

Java Convert ZonedDateTime to String Example

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

/**
 * Program to demonstrate ZonedDateTime Class APIs.
 * @author javaguides.net
 *
 */
public class ZonedDateTimeExample {
 
    public static void main(String[] args) {
        convertorformatZonedDateTimetoString();
    }

    private static void convertorformatZonedDateTimetoString() {
         // ISO pattern
        ZonedDateTime dateTime = ZonedDateTime.now();
        System.out.println(dateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));

        // 'yyyy-MMM-dd HH:mm:ss z' pattern
        System.out.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss z")));

        // 'yyyy-MM-dd KK:mm:ss a' pattern
        System.out.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd KK:mm:ss a")));

       // 'cccc, MMMM dd, yyyy KK:mm a' pattern
        System.out.println(dateTime.format(DateTimeFormatter.ofPattern("cccc, MMMM dd, yyyy KK:mm a")));
    }
}
Output:
2018-08-11T11:31:27.531+05:30[Asia/Calcutta]
2018-Aug-11 11:31:27 IST
2018-08-11 11:31:27 AM
Saturday, August 11, 2018 11:31 AM

Reference

Comments