Java Data Type How to - Format and parse yyyy-MM-dd HH:mm:ss vs 2000-02-01 12:23:34








Question

We would like to know how to format and parse yyyy-MM-dd HH:mm:ss vs 2000-02-01 12:23:34.

Answer

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
/*from w w w .  ja v a2s.  co  m*/
public class Main {

  public static void main(String[] args) {
    
    System.out.println(formatDateTime(LocalDateTime.now()));
    System.out.println(parse("2000-02-01 12:23:34"));
  }

  private static final String PATTERN = "yyyy-MM-dd HH:mm:ss";
  private static final DateTimeFormatter FMT = new DateTimeFormatterBuilder().appendPattern(PATTERN).toFormatter();
  
  public static String formatDateTime(LocalDateTime dateTime){
      String text = "";
      if(dateTime != null){
          return dateTime.format(FMT);
      }
      return text;
  }


  public static LocalDateTime parse(String text) {
      LocalDateTime dt = null;
      if(text != null && text.length() == PATTERN.length()){
          dt = LocalDateTime.parse(text, FMT);
      }
      return dt;
  }
}

The code above generates the following result.