In this source code example, we will you how to format a Date or LocalDateTime into yyyy-MM-dd HH:mm:ss format in Java.
Java format Date to yyyy-MM-dd HH:mm:ss
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class Main {
public static void main(String[] args) {
System.out.println("Before JDK 8:");
// yyyy-MM-dd
Date date = new Date();
SimpleDateFormat formatterD1 = new SimpleDateFormat("yyyy-MM-dd");
String d1 = formatterD1.format(date);
System.out.println(d1);
// yyyy-MM-dd HH:mm:ss
SimpleDateFormat formatterD2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String d2 = formatterD2.format(date);
System.out.println(d2);
System.out.println("\nStarting with JDK 8:");
// yyyy-MM-dd
LocalDate localDate = LocalDate.now();
DateTimeFormatter formatterLocalDate = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String ld1 = formatterLocalDate.format(localDate);
System.out.println(ld1);
// yyyy-MM-dd HH:mm:ss
LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter formatterLocalDateTime =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String ldt1 = formatterLocalDateTime.format(localDateTime);
System.out.println(ldt1);
}
}
Output:
Before JDK 8:
2021-11-10
2021-11-10 16:54:22
Starting with JDK 8:
2021-11-10
2021-11-10 16:54:22
Date
Java
java examples
LocalDateTime
Comments
Post a Comment