DateFormat DateFormat 是日期/時間格式化子類的抽象類,它以與語言無關的方式格式化並解析日期或時間。
SimpleDateFormat SimpleDateFormat
是一個以與語言環境有關的方式來格式化和解析日期的具體類。
DateTimeFormatter 對 LocalDateTime進行格式化
Date date = new Date(); date.setYear(118);// 2018 date.setMonth(8);// 9 date.setDate(8); date.setHours(8); date.setMinutes(8); date.setSeconds(8); // d.setTime(1470230414353l); System.out.println(date);// Sat Sep 08 08:08:08 CST 2018
DateFormat
String dateStr = DateFormat.getDateInstance().format(date); System.out.println(dateStr);// 2018-9-8 dateStr = DateFormat.getDateInstance(DateFormat.DEFAULT).format(date); System.out.println(dateStr);// 2018-9-8 dateStr = DateFormat.getDateInstance(DateFormat.FULL).format(date); System.out.println(dateStr);// 2018年9月8日 星期六 dateStr = DateFormat.getDateInstance(DateFormat.MEDIUM).format(date); System.out.println(dateStr);// 2018-9-8 dateStr = DateFormat.getDateInstance(DateFormat.SHORT).format(date); System.out.println(dateStr);// 18-9-8
SimpleDateFormat
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateStr = format.format(date); System.out.println(dateStr);// 2018-09-08 20:08:08
字符串解析為Date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date endDate = sdf.parse("2018-08-08"); System.out.println(endDate);//Wed Aug 08 00:00:00 CST 2018
DateTimeFormatter
//利用DateTimeFormatter進行 LocalDateTime與String互轉 {//LocalDateTime轉String(LocalDate,LocalTime類似) DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime localDateTime = LocalDateTime.now(); String localDateTimeStr = dtf.format(localDateTime); System.out.println("LocalDateTime轉成String類型的時間:" + localDateTimeStr);//2020-06-01 13:23:32 System.out.println("LocalDateTime轉成String類型的時間:" + localDateTime.toString());//2020-06-01T13:23:32.430 } {//String轉LocalDateTime(LocalDate,LocalTime類似) DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime localDateTime = LocalDateTime.parse("2018-06-01 10:12:05", dtf); System.out.println("String類型的時間轉成LocalDateTime:" + localDateTime);//2018-06-01T10:12:05 }
日期和時間模式表達方法
在使用SimpleDateFormat的時候,需要通過字母來描述時間元素,並組裝成想要的日期和時間模式。常用的時間元素和字母的對應表如下:

模式字母通常是重復的,其數量確定其精確表示。如下表是常用的輸出格式的表示方法。

注:
200601 v1.3 增加DateTimeFormatter