Java 时间格式化方法 DateTimeFormatter

在 Java 8 之前,一般使用 SimpleDateFormat 类进行时间格式化,但是这不是同步执行的方法,所以存在多线程执行不安全的问题。如果使用的是 Java 8 之前的 JDK,变成线程安全,就得通过线程加锁的方式解决。

一般我们会使用 Java 8 或者更高的版本,就可以使用 DateTimeFormatter  类代替SimpleDateFormat 类,这是一个线程安全的格式化工具类。

import java.time.format.DateTimeFormatter;
import java.time.LocalDate;

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate nowDate
= LocalDate.now(); String nowStr = dtf.format(nowDate); System.out.println(nowStr);

 

posted @ 2022-12-01 10:37  heroljy  阅读(800)  评论(0编辑  收藏  举报