JAVA 格式化日期、時(shí)間的方法
使用 DateFormat 格式化日期、時(shí)間
DateFormat 也是一個(gè)抽象類,它也提供了如下幾個(gè)類方法用于獲取 DateFormat 對(duì)象。
getDateInstance():返回一個(gè)日期格式器,它格式化后的字符串只有日期,沒(méi)有時(shí)間。該方法可以傳入多個(gè)參數(shù),用于指定日期樣式和 Locale 等參數(shù);如果不指定這些參數(shù),則使用默認(rèn)參數(shù)。 getTimeInstance():返回一個(gè)時(shí)間格式器,它格式化后的字符串只有時(shí)間,沒(méi)有日期。該方法可以傳入多個(gè)參數(shù),用于指定時(shí)間樣式和 Locale 等參數(shù);如果不指定這些參數(shù),則使用默認(rèn)參數(shù)。 getDateTimeInstance():返回一個(gè)日期、時(shí)間格式器,它格式化后的字符串既有日期,也有時(shí)間。該方法可以傳入多個(gè)參數(shù),用于指定日期樣式、時(shí)間樣式和 Locale 等參數(shù);如果不指定這些參數(shù),則使用默認(rèn)參數(shù)。上面三個(gè)方法可以指定日期樣式、時(shí)間樣式參數(shù),它們是的4個(gè)靜態(tài)常量:FULL、LONG、MEDIUM 和 SHORT,通過(guò)這4個(gè)樣式參數(shù)可以控制生成的格式化字符串。看如下例子程序。
import java.util.*;import java.text.*;import static java.text.DateFormat.*;public class DateFormatTest { public static void main(String[] args) throws ParseException { // 需要被格式化的時(shí)間 Date dt = new Date(); // 創(chuàng)建兩個(gè)Locale,分別代表中國(guó)、美國(guó) Locale[] locales = { Locale.CHINA, Locale.US }; DateFormat[] df = new DateFormat[16]; // 為上面兩個(gè)Locale創(chuàng)建16個(gè)DateFormat對(duì)象 for (int i = 0; i < locales.length; i++) { df[i * 8] = DateFormat.getDateInstance(SHORT, locales[i]); df[i * 8 + 1] = DateFormat.getDateInstance(MEDIUM, locales[i]); df[i * 8 + 2] = DateFormat.getDateInstance(LONG, locales[i]); df[i * 8 + 3] = DateFormat.getDateInstance(FULL, locales[i]); df[i * 8 + 4] = DateFormat.getTimeInstance(SHORT, locales[i]); df[i * 8 + 5] = DateFormat.getTimeInstance(MEDIUM, locales[i]); df[i * 8 + 6] = DateFormat.getTimeInstance(LONG, locales[i]); df[i * 8 + 7] = DateFormat.getTimeInstance(FULL, locales[i]); } for (int i = 0; i < locales.length; i++) { String tip = i == 0 ? '----中國(guó)日期格式----' : '----美國(guó)日期格式----'; System.out.println(tip); System.out.println('SHORT格式的日期格式:' + df[i * 8].format(dt)); System.out.println('MEDIUM格式的日期格式:' + df[i * 8 + 1].format(dt)); System.out.println('LONG格式的日期格式:' + df[i * 8 + 2].format(dt)); System.out.println('FULL格式的日期格式:' + df[i * 8 + 3].format(dt)); System.out.println('SHORT格式的時(shí)間格式:' + df[i * 8 + 4].format(dt)); System.out.println('MEDIUM格式的時(shí)間格式:' + df[i * 8 + 5].format(dt)); System.out.println('LONG格式的時(shí)間格式:' + df[i * 8 + 6].format(dt)); System.out.println('FULL格式的時(shí)間格式:' + df[i * 8 + 7].format(dt)); } }}
上面程序共創(chuàng)建了16個(gè) DateFormat 對(duì)象,分別為中國(guó)、美國(guó)兩個(gè) Locale 各創(chuàng)建8個(gè) DateFormat 對(duì)象,分別是 SHORT、MEDIUM、LONG、FULL 四種樣式的日期格式器、時(shí)間格式器。運(yùn)行上面程序,會(huì)看到如下所示的效果。
----中國(guó)日期格式----SHORT格式的日期格式:20-2-11MEDIUM格式的日期格式:2020-2-11LONG格式的日期格式:2020年2月11日FULL格式的日期格式:2020年2月11日 星期二SHORT格式的時(shí)間格式:下午2:26MEDIUM格式的時(shí)間格式:14:26:21LONG格式的時(shí)間格式:下午02時(shí)26分21秒FULL格式的時(shí)間格式:下午02時(shí)26分21秒 CST----美國(guó)日期格式----SHORT格式的日期格式:2/11/20MEDIUM格式的日期格式:Feb 11, 2020LONG格式的日期格式:February 11, 2020FULL格式的日期格式:Tuesday, February 11, 2020SHORT格式的時(shí)間格式:2:26 PMMEDIUM格式的時(shí)間格式:2:26:21 PMLONG格式的時(shí)間格式:2:26:21 PM CSTFULL格式的時(shí)間格式:2:26:21 PM CST
DateFormat 具有國(guó)際化的能力,同一個(gè)日期使用不同的 Locale 格式器格式化的效果完全不同,格式化后的字符串正好符合 Locale 對(duì)應(yīng)的本地習(xí)慣。
獲得了 DateFormat 之后,還可以調(diào)用它的 setLenient(boolean lenient) 方法來(lái)設(shè)置該格式器是否采用嚴(yán)格語(yǔ)法。舉例來(lái)說(shuō),如果采用不嚴(yán)格的日期語(yǔ)法(該方法的參數(shù)為true),對(duì)于字符串'2004-2-31'將會(huì)轉(zhuǎn)換成2004年3月2日:如果采用嚴(yán)格的日期語(yǔ)法,解析該字符串時(shí)將拋出異常。
DateFormat 的 parse() 方法可以把一個(gè)字符串解析成 Date 對(duì)象,但它要求被解析的字符串必須符合日期字符串的要求,否則可能拋出 ParseExcepuon 異常。例如,如下代碼片段:
String str1 = '2017/10/07';String str2 = '2017年10月07日';// 下面輸出 Sat Oct 07 00:00:00 CST 2017System.out.println(DateFormat.getDateInstance().parse(str2));// 下面輸出 Sat Oct 07 00:00:00 CST 2017System.out.println(DateFormat.getDateInstance(SHORT).parse(str1));// 下面拋出 ParseException異常System.out.println(DateFormat.getDateInstance().parse(str1));
上面代碼中最后一行代碼解析日期字符串時(shí)引發(fā) ParseException 異常,因?yàn)?2017/10/07'是一個(gè) SHORT 樣式的日期字符串,必須用 SHORT 樣式的 DateFormat 實(shí)例解析,否則將拋出異常。
使用 SimpleDateFormat 格式化日期
前面介紹的 DateFormat 的方法可以把字符串解析成 Date 對(duì)象,但實(shí)際上 DateFormat 的 parse() 方法不夠靈活一一它要求被解析的字符串必須滿足特定的格式!為了更好地格式化日期、解析日期字符串,Java 提供了 SimpleDateFormat 類。
SimpleDateFormat 是 DateFormat 的子類,正如它的名字所暗示的,它是“簡(jiǎn)單”的日期格式器。很多讀者對(duì)“簡(jiǎn)單”的日期格式器不屑一顧,實(shí)際上 SimpleDateFormat 比 DateFormat 更簡(jiǎn)單,功能更強(qiáng)大。
SimpleDateFormat 可以非常靈活地格式化 Date,也可以用于解析各種格式的日期字符串。創(chuàng)建 SimpleDateFormat 對(duì)象時(shí)需要傳入一個(gè) pattern 字符串,這個(gè) pattern 不是正則表達(dá)式,而是一個(gè)日期模板字符串。
import java.text.*;import java.util.*;public class SimpleDateFormatTest { public static void main(String[] args) throws ParseException { Date d = new Date(); // 創(chuàng)建一個(gè)SimpleDateFormat對(duì)象 SimpleDateFormat sdf1 = new SimpleDateFormat('Gyyyy年中第D天'); // 將d格式化成日期,輸出:公元2017年中第282天 String dateStr = sdf1.format(d); System.out.println(dateStr); // 一個(gè)非常特殊的日期字符串 String str = '14###3月##21'; SimpleDateFormat sdf2 = new SimpleDateFormat('y###MMM##d'); // 將日期字符串解析成日期,輸出:Fri Mar 21 00:00:00 CST 2014 System.out.println(sdf2.parse(str)); }}
從上面程序中可以看出,使用 SimpleDateFormat 可以將日期格式化成形如“公元2014年中第101天”這樣的字符串,也可以把形如“14###3月##21”這樣的字符串解析成日期,功能非常強(qiáng)大。
SimpleDateFormat 把日期格式化成怎樣的字符串,以及能把怎樣的字符串解析成 Date,完全取決于創(chuàng)建該對(duì)象時(shí)指定的 pattern 參數(shù),pattern 是一個(gè)使用日期字段占位符的日期模板。
如果讀者想知道 SimpleDateFormat 支持哪些日期、時(shí)間占位符,可以查閱 API 文檔中 SimpleDateFormat 類的說(shuō)明,此處不再贅述。
Java 8 新增的日期、時(shí)間格式器
Java 8 新增的日期、時(shí)間 API 里不僅包括了 Instant、LocalDate、LocalDateTime、LocalTime 等代表日期、時(shí)間的類,而且在 java.time.format 包下提供了一個(gè) DateTimeFormatter 格式器類,該類相當(dāng)于前面介紹的 DateFormat 和 SimpleDateFormat 的合體,功能非常強(qiáng)大。
與 DateFormat、SimpleDateFormat 類似,DateTimeFormatter 不僅可以將日期、時(shí)間對(duì)象格式化成字符串,也可以將特定格式的字符串解析成日期、時(shí)間對(duì)象。
為了使用 DateTimeFormatter 進(jìn)行格式化或解析,必須先獲取 DateTimeFormatter 對(duì)象,獲取 DateTimeFormatter 對(duì)象有如下三種常見(jiàn)的方式。
直接使用靜態(tài)常量創(chuàng)建 DateTimeFormatter 格式器。DateTimeFormatter 類中包含了大量形如 ISO_LOCAL_DATE、ISO_LOCAL_TIME、ISO_LOCAL_DATE_TIME 等靜態(tài)常量,這些靜態(tài)常量本身就是 DateTimeFormatter 實(shí)例。 使用代表不同風(fēng)格的枚舉值來(lái)創(chuàng)建 DateTimeFormatter 格式器。在 FormatStyle 枚舉類中定義了 FULL、LONG、MEDIUM、SHORT 四個(gè)枚舉值,它們代表日期、時(shí)間的不同風(fēng)格。 根據(jù)模式字符串來(lái)創(chuàng)建 DateTmeFormatter 格式器。類似于 SimpleDateFormat,可以采用模式字符串來(lái)創(chuàng)建 DateTimeFormatter,如果需要了解支持哪些模式字符串,則需要參該類的 API 文檔。使用 DateTimeFormatter 完成格式化
使用 DateTimeFormatter 將日期、時(shí)間(LocalDate、LocalDateTime、LocalTime等實(shí)例)格式化為字符串,可通過(guò)如下兩種方式。
調(diào)用 DateTimeFormatter 的 format(TemporalAccessor temporal) 方法執(zhí)行格式化,其中 LocalDate、LocalDateTime、LocalTime 等類都是 TemporalAccessor 接口的實(shí)現(xiàn)類。 調(diào)用 LocalDate、LocalDateTime、LocalTime 等日期、時(shí)間對(duì)象的 format(DateTimeFormatter formatter) 方法執(zhí)行格式化。上面兩種方式的功能相同,用法也基本相似,如下程序示范了使用 DateTimeFormatter 來(lái)格式化日期、時(shí)間。
import java.time.*;import java.time.format.*;public class NewFormatterTest{ public static void main(String[] args){ DateTimeFormatter[] formatters = new DateTimeFormatter[]{ // 直接使用常量創(chuàng)建DateTimeFormatter格式器 DateTimeFormatter.ISO_LOCAL_DATE, DateTimeFormatter.ISO_LOCAL_TIME, DateTimeFormatter.ISO_LOCAL_DATE_TIME, // 使用本地化的不同風(fēng)格來(lái)創(chuàng)建DateTimeFormatter格式器 DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM), DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG), // 根據(jù)模式字符串來(lái)創(chuàng)建DateTimeFormatter格式器 DateTimeFormatter.ofPattern('Gyyyy%%MMM%%dd HH:mm:ss') }; LocalDateTime date = LocalDateTime.now(); // 依次使用不同的格式器對(duì)LocalDateTime進(jìn)行格式化 for(int i = 0 ; i < formatters.length ; i++){ // 下面兩行代碼的作用相同 System.out.println(date.format(formatters[i])); System.out.println(formatters[i].format(date)); } }}
上面程序使用三種方式創(chuàng)建了6個(gè) DateTimeFormatter 對(duì)象,然后程序中兩行粗體字代碼分別使用不同方式來(lái)格式化日期。運(yùn)行上面程序,會(huì)看到如下所示的效果。
2020-02-112020-02-1117:13:00.30317:13:00.3032020-02-11T17:13:00.3032020-02-11T17:13:00.3032020年2月11日 星期二 17:13:002020年2月11日 星期二 17:13:002020年2月11日2020年2月11日公元2020%%二月%%11 17:13:00公元2020%%二月%%11 17:13:00
可以看出,使用 DateTimeFormatter 進(jìn)行格式化,也可使用模式字符串對(duì)日期、時(shí)間進(jìn)行自定義格式化,由此可見(jiàn),功能完全覆蓋了傳統(tǒng)的 DateFormat、SimpleDateFormate 的功能。
提示:有些時(shí)候,讀者可能還需要使用傳統(tǒng)的 DateFormat 來(lái)執(zhí)行格式化,DateTimeFormatter 則提供了一個(gè) toFormat() 方法,該方法可以獲取 DateTimeFormatter 對(duì)應(yīng)的 Format 對(duì)象。
使用 DateTimeFormatter 解析字符串
為了使用 DateTimeFormatter 將指定格式的字符串解析成日期、時(shí)間對(duì)象(LocalDate、LocalDateTime、LocalTime 等實(shí)例),可通過(guò)日期、時(shí)間對(duì)象提供的 parse(CharSequence text,DateTimeFormatter formatter) 方法進(jìn)行解析。
如下程序示范了使用 DateTimeFormatter 解析日期、時(shí)間字符串。
import java.time.*;import java.time.format.*;public class NewFormatterParse { public static void main(String[] args) { // 定義一個(gè)任意格式的日期時(shí)間字符串 String str1 = '2014==04==12 01時(shí)06分09秒'; // 根據(jù)需要解析的日期、時(shí)間字符串定義解析所用的格式器 DateTimeFormatter fomatter1 = DateTimeFormatter.ofPattern('yyyy==MM==dd HH時(shí)mm分ss秒'); // 執(zhí)行解析 LocalDateTime dt1 = LocalDateTime.parse(str1, fomatter1); System.out.println(dt1); // 輸出 2014-04-12T01:06:09 // ---下面代碼再次解析另一個(gè)字符串--- String str2 = '2014$$$4月$$$13 20小時(shí)'; DateTimeFormatter fomatter2 = DateTimeFormatter.ofPattern('yyy$$$MMM$$$dd HH小時(shí)'); LocalDateTime dt2 = LocalDateTime.parse(str2, fomatter2); System.out.println(dt2); // 輸出 2014-04-13T20:00 }}
上面程序中定義了兩個(gè)不同格式的日期、時(shí)間字符串,為了解析它們,程序分別使用對(duì)應(yīng)的格式字符串創(chuàng)建了 DateTmeFormatter 對(duì)象,這樣 DateTimeFormatter 即可按該格式字符串將日期、時(shí)間字符串解析成 LocalDateTime 對(duì)象。編譯、運(yùn)行該程序,即可看到兩個(gè)日期、時(shí)間字符串都被成功地解析成 LocalDateTime。
以上就是JAVA 格式化日期、時(shí)間的方法的詳細(xì)內(nèi)容,更多關(guān)于JAVA 格式化日期、時(shí)間的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 使用XSL將XML文檔中的CDATA注釋輸出為HTML文本2. PHP循環(huán)與分支知識(shí)點(diǎn)梳理3. 使用HttpClient增刪改查ASP.NET Web API服務(wù)4. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案5. 告別AJAX實(shí)現(xiàn)無(wú)刷新提交表單6. jsp實(shí)現(xiàn)簡(jiǎn)單用戶7天內(nèi)免登錄7. .NET反向代理組件YARP介紹8. 小技巧處理div內(nèi)容溢出9. .NET Core中使用gRPC的方法10. 輕松學(xué)習(xí)XML教程
