# DateTimeFormatter
# 介绍
与传统的 SimpleDateFormat 相比,DateTimeFormat 是线程安全的
# 创建对象
public class DateTimeFormatTest {
public static void main(String[] args) {
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-mm-dd hh:mm:ss");
}
}
# 格式化
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatTest {
public static void main(String[] args) {
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-mm-dd hh:mm:ss");
String format = pattern.format(LocalDateTime.now());
System.out.println(format);
}
}
# 格式化方式2
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatTest {
public static void main(String[] args) {
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-mm-dd hh:mm:ss");
LocalDateTime now = LocalDateTime.now();
String s = now.format(pattern);
System.out.println(s);
}
}
# 将字符串解析成LocalDateTime
public class DateTimeFormatTest {
public static void main(String[] args) {
//注意 这里不用 HH 24小时的 下面解析是会报错的
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
String s = now.format(pattern);
System.out.println(s);
LocalDateTime parse = LocalDateTime.parse(s, pattern);
System.out.println(parse);
}
}