Custom Date Format with Optional

Description

When defining custom date time format we can use symbols [ and ] to mark an optional section.

A pattern enclosed within an optional section is output only if information is available for all its elements.

Example

The following code shows how to use an optional format.


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
/* w  w w.  j a v  a2  s  .  c om*/
public class Main {

  public static void main(String[] args) {
    String pattern = "MM/dd/yyyy[ 'at' HH:mm:ss]";
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern);

    LocalDate ld = LocalDate.of(2014, Month.JUNE, 30);
    LocalTime lt = LocalTime.of(17, 30, 12);
    LocalDateTime ldt = LocalDateTime.of(ld, lt);

    String str1 = fmt.format(ld);
    System.out.println(str1);

    String str2 = fmt.format(ldt);

    System.out.println(str2);
  }
}

The code above generates the following result.





















Home »
  Java Date Time »
    Tutorial »




Java Date Time Tutorial