Java - Date time Classes format( ) Method

Introduction

You can format a datetime object using its format() method.

The format() method takes an object of the DateTimeFormatter class.

The following code uses ISO_DATE formatter with format() method.

Demo

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

public class Main {
  public static void main(String[] args) {
    LocalDate ld = LocalDate.now();
    String ldStr = ld.format(DateTimeFormatter.ISO_DATE);
    System.out.println("Local Date: " + ldStr);

    OffsetDateTime odt = OffsetDateTime.now();
    String odtStr = odt.format(DateTimeFormatter.ISO_DATE);
    System.out.println("Offset Datetime: " + odtStr);

    ZonedDateTime zdt = ZonedDateTime.now();
    String zdtStr = zdt.format(DateTimeFormatter.ISO_DATE);
    System.out.println("Zoned Datetime: " + zdtStr);
  }//from  w ww  .  j a  va2  s.  c o  m
}

Result

Related Topic