Java Data Type How to - Format LocalDateTime with dd/MM/yyyy as 01/04/2014








Question

We would like to know how to format LocalDateTime with dd/MM/yyyy as 01/04/2014.

Answer

import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
/*w ww  .j  a v  a 2 s  . c o  m*/
public class Main {
  public static void main(String[] args) {
    // 2014-04-01 10:45
    LocalDateTime dateTime = LocalDateTime.of(2014, Month.APRIL, 1, 10, 45);

    // using a custom pattern (01/04/2014)
    String asCustomPattern = dateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
    
    System.out.println(asCustomPattern);
  }
}

The code above generates the following result.