java.text.DateFormat 是抽象基類,提供預定義風格 (SHORT/MEDIUM/LONG/FULL) 的工廠方法,實際返回 SimpleDateFormat 實例。適用於快速獲得本地化標準格式,不需手寫模式。
| 風格常量 | 日期示例 | 時間示例 |
|---|---|---|
| SHORT | 13-9-19 | 下午2:22 |
| MEDIUM | 2013-9-19 | 14:22:30 |
| LONG | 2013年9月19日 | 14:22:30 CST |
| FULL | 2013年9月19日 星期四 | 14:22:30 中國標準時間 |
getInstance() // SHORT 日期+時間
getDateInstance() // MEDIUM 日期
getDateInstance(int style) // 指定風格日期
getDateInstance(int style, Locale) // 指定風格+區域日期
getTimeInstance() // MEDIUM 時間
getTimeInstance(int style) // 指定風格時間
getTimeInstance(int style, Locale) // 指定風格+區域時間
getDateTimeInstance() // MEDIUM 日期+時間
getDateTimeInstance(int dStyle, int tStyle) // 指定風格日期+時間
getDateTimeInstance(int dStyle, int tStyle, Locale) // 指定風格+區域日期+時間
private static DateFormat get(int timeStyle, int dateStyle, int flags, Locale loc) {
// flags: 1=時間, 2=日期, 3=日期時間
// 校驗 style 範圍 0-3
// 嘗試 SPI 獲取提供者實現
return new SimpleDateFormat(timeStyle, dateStyle, loc);
}
JDK 通過 LocaleServiceProvider SPI 允許第三方擴展本地化格式化實現。
Date date = new Date();
Locale cn = Locale.SIMPLIFIED_CHINESE;
// 時間風格
System.out.println("SHORT: " + DateFormat.getTimeInstance(DateFormat.SHORT, cn).format(date));
System.out.println("MEDIUM: " + DateFormat.getTimeInstance(DateFormat.MEDIUM, cn).format(date));
System.out.println("LONG: " + DateFormat.getTimeInstance(DateFormat.LONG, cn).format(date));
System.out.println("FULL: " + DateFormat.getTimeInstance(DateFormat.FULL, cn).format(date));
// 日期風格
System.out.println("Date SHORT: " + DateFormat.getDateInstance(DateFormat.SHORT, cn).format(date));
System.out.println("Date FULL: " + DateFormat.getDateInstance(DateFormat.FULL, cn).format(date));
// 日期時間組合
System.out.println("DateTime LONG/SHORT: " +
DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT, cn).format(date));
format(Date date) → String // 最常用
format(Object obj, StringBuffer, FieldPosition) // 底層多態入口
parse(String source) → Date // 全字符串解析
parse(String source, ParsePosition pos) → Date // 部分解析,pos 更新索引
setTimeZone(TimeZone) 設置時區setLenient(boolean) 寬鬆模式 (默認 true,允許 2月30日 自動轉 3月2日)setCalendar(Calendar) 替換底層日曆 (罕用)DateFormat.getXxxInstance()new SimpleDateFormat(pattern)java.time.format.DateTimeFormatter (線程安全、功能更強)