Java日期格式化類:DateTimeFormatter與SimpleDateFormat

一個是線程安全的,一個是線程不安全的。先來看看兩者源碼:(看看註釋就一目瞭然了)

DateTimeFormatter

/* @implSpec
 * This class is immutable and thread-safe.
 *
 * @since 1.8
 */
public final class DateTimeFormatter{...}

SimpleDateFormat

/*
* <p>
 * Date formats are not synchronized.
 * It is recommended to create separate format instances for each thread.
 * If multiple threads access a format concurrently, it must be synchronized
 * externally.
 *
 * @see          java.util.Calendar
 * @see          java.util.TimeZone
 * @see          DateFormat
 * @see          DateFormatSymbols
 * @author       Mark Davis, Chen-Lieh Huang, Alan Liu
 */
public class SimpleDateFormat extends DateFormat {...}

再看使用示例:

DateTimeFormatter df= DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime ld=LocalDateTime.now();
System.out.println(ld.format(df.ISO_LOCAL_TIME.ISO_TIME));

DateFormat dfs = new SimpleDateFormat("yy.MM.dd HH:mm:ss");
System.out.println(dfs.format(new Date()));
System.out.println(dfs.parseObject("2020.1.4 1:2:2"));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章