Format ZonedDateTime to String in Java 8

Learn to format a ZonedDateTime to string using ZonedDateTime.format(DateTimeFormatter) method in Java 8.

1. ZonedDateTime to String – inbuilt formatters

DateTimeFormatter class has many inbuilt formatters which we can use in most the cases e.g.

  • ISO_ZONED_DATE_TIME
  • ISO_DATE_TIME
  • ISO_INSTANT
  • RFC_1123_DATE_TIME

A full list of formatters are listed in here.

Java example to use prebuilt formatter to format a zoned datetime instance.

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

public class Main 
{
    public static void main(String[] args)
    {
        ZonedDateTime zonedDateTime = ZonedDateTime.of(LocalDateTime.now(), 
        								ZoneId.of("America/Los_Angeles"));
        
        //default pattern - ISO_ZONED_DATE_TIME
        System.out.println(zonedDateTime);
        
        System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
        
        System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_DATE_TIME));
        
        System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_INSTANT));
        
        System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        
        System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE));
        
        System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_LOCAL_TIME));
    }
}

Program output.

2019-04-02T14:32:47.199-07:00[America/Los_Angeles]
2019-04-02T14:32:47.199-07:00[America/Los_Angeles]
2019-04-02T14:32:47.199-07:00[America/Los_Angeles]
2019-04-02T21:32:47.199Z
2019-04-02T14:32:47.199
2019-04-02
14:32:47.199

2. ZonedDateTime to String – custom formatter

Using DateTimeFormatter.ofPattern, we can create our own custom formatters and use them just like above.

Java example to use custom formatter to format a zoned datetime instance to string.

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

public class Main 
{
    public static void main(String[] args)
    {
        ZonedDateTime zonedDateTime = ZonedDateTime.now();
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy - HH:mm:ss z");
        
        String formattedString = zonedDateTime.format(formatter);
        
        System.out.println(formattedString);
    }
}

Program output.

04/02/2019 - 14:36:37 IST

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.