java 解析日期格式_日期/时间格式/解析,Java 8样式
java 解析日期格式
自Java 幾乎 開始以來,Java開發(fā)人員就通過java.util.Date類(自JDK 1.0起)和java.util.Calendar類(自JDK 1.1起 )來處理日期和時間。 在這段時間內(nèi),成千上萬(甚至數(shù)百萬)的Java開發(fā)人員已使用java.text.DateFormat和java.text.SimpleDateFormat格式化并解析了Java日期和時間。 鑒于多年來這樣做的頻率,不足為奇的是,有很多關(guān)于這些類的日期和時間的解析和格式設(shè)置的 在線 示例和教程 。 經(jīng)典的Java教程在“ 格式設(shè)置”課程 ( Dates and Times )中介紹了這些java.util和java.text類。 Java教程中新的Date Time路徑涵蓋了Java 8中有關(guān)日期和時間以及它們的格式和解析的新類。 這篇文章提供了一些實際的例子。
在通過示例演示Java 8樣式的日期/時間解析/格式化之前,先比較一下DateFormat / SimpleDateFormat和DateTimeFormatter的Javadoc描述。 下表包含可區(qū)分的信息,這些信息可通過比較每個格式類的Javadoc來直接或間接收集。 從此表中可能最重要的觀察結(jié)果是,新的DateTimeFormatter是線程安全的且不可變的,并且DateTimeFormatter提供了用于解析和格式化日期和時間的API的概述。
| 目的 | “以與語言無關(guān)的方式格式化和解析日期或時間” | “用于打印和解析日期時間對象的格式化程序。” |
| 主要用于 | java.util.Date java.util.Calendar | java.time.LocalDate java.time.LocalTime java.time.LocalDateTime java.time.OffsetTime java.time.OffsetDateTime java.time.ZonedDateTime java.time.Instant |
| 線程安全 | “日期格式不同步。” | “此類是不可變的并且是線程安全的。” |
| 直接格式化 | 格式(日期) | 格式(TemporalAccessor) |
| 直接解析 | parse(String) | 解析(CharSequence,TemporalQuery) |
| 間接格式化 | 無[除非您使用Groovy的Date.format(String)擴展名) | LocalDate.format(DateTimeFormatter) LocalTime.format(DateTimeFormatter) LocalDateTime.format(DateTimeFormatter) OffsetTime.format(DateTimeFormatter) OffsetDateTime.format(DateTimeFormatter) ZonedDateTime.format(DateTimeFormatter) |
| 間接解析 | 無[除非您使用不推薦使用的Date.parse(String)或Groovy的Date.parse(String,String)擴展名] | LocalDate.parse(CharSequence,DateTimeFormatter) LocalTime.parse(CharSequence,DateTimeFormatter) LocalDateTime.parse(CharSequence,DateTimeFormatter) OffsetTime.parse(CharSequence,DateTimeFormatter) OffsetDateTime.parse(CharSequence,DateTimeFormatter) ZonedDateTime.parse(CharSequence,DateTimeFormatter) |
| 國際化 | java.util.Locale | java.util.Locale |
| 時區(qū) | java.util.TimeZone | java.time.ZoneId java.time.ZoneOffset |
| 預(yù)定義格式器 | 沒有,但是為常見實例提供了靜態(tài)便利方法: getDateInstance() getDateInstance(int) getDateInstance(int,Locale) getDateTimeInstance() getDateTimeInstance(int,int) getDateTimeInstance(int,int,Locale) getInstance() getTimeInstance() getTimeInstance(int) getTimeInstance(int,Locale) | ISO_LOCAL_DATE ISO_LOCAL_TIME ISO_LOCAL_DATE_TIME ISO_OFFSET_DATE ISO_OFFSET_TIME ISO_OFFSET_DATE_TIME ISO_ZONED_DATE_TIME BASIC_ISO_DATE ISO_DATE ISO_DATE_TIME ISO_ORDINAL_DATE ISO_INSTANT ISO_WEEK_DATE RFC_1123_DATE_TIME |
這篇文章的其余部分將使用示例演示如何使用java.time構(gòu)造在Java 8中格式化和解析日期。 這些示例將使用以下字符串模式和實例。
/** Pattern to use for String representation of Dates/Times. */ private final String dateTimeFormatPattern = "yyyy/MM/dd HH:mm:ss z";/*** java.util.Date instance representing now that can* be formatted using SimpleDateFormat based on my* dateTimeFormatPattern field.*/ private final Date now = new Date();/*** java.time.ZonedDateTime instance representing now that can* be formatted using DateTimeFormatter based on my* dateTimeFormatPattern field.** Note that ZonedDateTime needed to be used in this example* instead of java.time.LocalDateTime or java.time.OffsetDateTime* because there is zone information in the format provided by* my dateTimeFormatPattern field and attempting to have* DateTimeFormatter.format(TemporalAccessor) instantiated* with a format pattern that includes time zone details* will lead to DateTimeException for instances of* TemporalAccessor that do not have time zone information* (such as LocalDateTime and OffsetDateTime).*/ private final ZonedDateTime now8 = ZonedDateTime.now();/*** String that can be used by both SimpleDateFormat and* DateTimeFormatter to parse respective date/time instances* from this String.*/ private final String dateTimeString = "2014/09/03 13:59:50 MDT";在Java 8之前,用于日期和時間的標準Java方法是通過Date和Calendar類,而用于解析和格式化日期的標準方法是通過DateFormat和SimpleDateFormat 。 下一個代碼清單演示了這些經(jīng)典方法。
使用SimpleDateFormat格式化和解析Java日期
/*** Demonstrate presenting java.util.Date as String matching* provided pattern via use of SimpleDateFormat.*/ public void demonstrateSimpleDateFormatFormatting() {final DateFormat format = new SimpleDateFormat(dateTimeFormatPattern);final String nowString = format.format(now);out.println("Date '" + now + "' formatted with SimpleDateFormat and '"+ dateTimeFormatPattern + "': " + nowString); }/*** Demonstrate parsing a java.util.Date from a String* via SimpleDateFormat.*/ public void demonstrateSimpleDateFormatParsing() {final DateFormat format = new SimpleDateFormat(dateTimeFormatPattern);try{final Date parsedDate = format.parse(dateTimeString);out.println("'" + dateTimeString + "' is parsed with SimpleDateFormat as " + parsedDate);}// DateFormat.parse(String) throws a checked exceptioncatch (ParseException parseException){out.println("ERROR: Unable to parse date/time String '"+ dateTimeString + "' with pattern '"+ dateTimeFormatPattern + "'.");} }在Java 8中,首選日期/時間類不再位于java.util包中,并且首選日期/時間處理類現(xiàn)在位于java.time包中。 同樣,首選的日期/時間格式/解析類不再位于java.text包中,而是來自java.time.format包。
java.time包提供了許多用于對日期和/或時間進行建模的類。 這些包括僅對日期建模的類(無時間信息),僅對時間建模的類(無日期信息),對日期和時間信息進行建模的類,使用時區(qū)信息的類以及不包含時區(qū)信息的類。 盡管類的特性(例如,是否支持日期或時間或時區(qū)信息)會影響可以應(yīng)用的模式,但格式化和解析這些方法的方法通常是相似的。 在本文中,我將ZonedDateTime類用作示例。 之所以選擇該選項,是因為它包含日期,時間和時區(qū)信息,并允許我使用一種匹配模式,該模式涉及所有三個特征,例如Date或Calendar實例。 這使得比較新舊方法變得更加容易。
DateTimeFormatter類提供了ofPattern方法,以基于所提供的日期/時間模式String提供DateTimeFormatter的實例。 然后可以在該DateTimeFormatter實例上調(diào)用一種格式方法,以獲取日期和/或時間信息,格式為與提供的模式匹配的String。 下一個代碼清單說明了基于提供的模式從ZonedDateTime格式化String這種方法。
將ZonedDateTime格式化為字符串
/*** Demonstrate presenting ZonedDateTime as a String matching* provided pattern via DateTimeFormatter and its* ofPattern(String) method.*/ public void demonstrateDateTimeFormatFormatting() {final DateTimeFormatter formatter =DateTimeFormatter.ofPattern(dateTimeFormatPattern);final String nowString = formatter.format(now8);out.println(now8 + " formatted with DateTimeFormatter and '"+ dateTimeFormatPattern + "': " + nowString); }基于模式從字符串中解析日期/時間類很容易完成。 有兩種方法可以實現(xiàn)。 一種方法是將DateTimeFormatter的實例傳遞給靜態(tài)ZonedDateTime.parse(CharSequence,DateTimeFormatter)方法,該方法返回從提供的字符序列派生并基于提供的模式的ZonedDateTime實例。 下一個代碼清單對此進行了說明。
使用靜態(tài)ZonedDateTime.parse方法從字符串解析ZonedDateTime
/*** Demonstrate parsing ZonedDateTime from provided String* via ZonedDateTime's parse(String, DateTimeFormatter) method.*/ public void demonstrateDateTimeFormatParsingTemporalStaticMethod() {final DateTimeFormatter formatter =DateTimeFormatter.ofPattern(dateTimeFormatPattern);final ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateTimeString, formatter);out.println("'" + dateTimeString+ "' is parsed with DateTimeFormatter and ZonedDateTime.parse as "+ zonedDateTime); }從字符串解析ZonedDateTime第二種方法是通過DateTimeFormatter的parse(CharSequence,TemporalQuery <T>)方法。 在下面的代碼清單中對此進行了說明,該清單也提供了演示Java 8 方法引用的用法的機會(請參見ZonedDateTime::from )。
使用DateTimeFormatter.parse方法從字符串解析ZonedDateTime
/*** Demonstrate parsing ZonedDateTime from String* via DateTimeFormatter.parse(String, TemporaryQuery)* with the Temple Query in this case being ZonedDateTime's* from(TemporalAccessor) used as a Java 8 method reference.*/ public void demonstrateDateTimeFormatParsingMethodReference() {final DateTimeFormatter formatter =DateTimeFormatter.ofPattern(dateTimeFormatPattern);final ZonedDateTime zonedDateTime = formatter.parse(dateTimeString, ZonedDateTime::from);out.println("'" + dateTimeString+ "' is parsed with DateTimeFormatter and ZoneDateTime::from as "+ zonedDateTime); }很少有項目可以作為可以從Java 8開始的未開發(fā)項目。因此,將JDK 8之前的日期/時間類與JDK 8中引入的新日期/時間類連接在一起的類將很有幫助。例如,JDK 8的DateTimeFormatter可以通過DateTimeFormatter.toFormat()方法提供JDK 8之前的抽象Format類的降序?qū)嵗?下一個代碼清單中對此進行了演示。
從JDK 8的DateTimeFormatter訪問JDK 8之前的格式
/*** Demonstrate formatting ZonedDateTime via DateTimeFormatter,* but using implementation of Format.*/ public void demonstrateDateTimeFormatAndFormatFormatting() {final DateTimeFormatter formatter =DateTimeFormatter.ofPattern(dateTimeFormatPattern);final Format format = formatter.toFormat();final String nowString = format.format(now8);out.println("ZonedDateTime " + now + " formatted with DateTimeFormatter/Format (and "+ format.getClass().getCanonicalName() + ") and '"+ dateTimeFormatPattern + "': " + nowString); }該即時與兩個前JDK 8工作時類是特別重要的Date和Calendar結(jié)合類與JDK 8之所以引入新的日期和時間類Instant是如此重要的是, java.util.Date有方法從(即時)和toInstant()分別從Instant獲取Date和從Date獲取Instant 。 因為Instant在將Java 8之前的日期/時間處理遷移到Java 8基線非常重要,所以下一個代碼清單演示了Instant實例的格式和解析。
格式化和解析Instant實例
/*** Demonstrate formatting and parsing an instance of Instant.*/ public void demonstrateDateTimeFormatFormattingAndParsingInstant() {// Instant instances don't have timezone informationfinal Instant instant = now.toInstant();final DateTimeFormatter formatter =DateTimeFormatter.ofPattern(dateTimeFormatPattern).withZone(ZoneId.systemDefault());final String formattedInstance = formatter.format(instant);out.println("Instant " + instant + " formatted with DateTimeFormatter and '"+ dateTimeFormatPattern + "' to '" + formattedInstance + "'");final Instant instant2 =formatter.parse(formattedInstance, ZonedDateTime::from).toInstant();out.println(formattedInstance + " parsed back to " + instant2); }為了完整起見,所有上述示例均來自下一個代碼清單中顯示的示例類。
DateFormatDemo.java
package dustin.examples.numberformatdemo;import static java.lang.System.out;import java.text.DateFormat; import java.text.Format; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date;/*** Demonstrates formatting dates as strings and parsing strings* into dates and times using pre-Java 8 (java.text.SimpleDateFormat)* and Java 8 (java.time.format.DateTimeFormatter) mechanisms.*/ public class DateFormatDemo {/** Pattern to use for String representation of Dates/Times. */private final String dateTimeFormatPattern = "yyyy/MM/dd HH:mm:ss z";/*** java.util.Date instance representing now that can* be formatted using SimpleDateFormat based on my* dateTimeFormatPattern field.*/private final Date now = new Date();/*** java.time.ZonedDateTime instance representing now that can* be formatted using DateTimeFormatter based on my* dateTimeFormatPattern field.** Note that ZonedDateTime needed to be used in this example* instead of java.time.LocalDateTime or java.time.OffsetDateTime* because there is zone information in the format provided by* my dateTimeFormatPattern field and attempting to have* DateTimeFormatter.format(TemporalAccessor) instantiated* with a format pattern that includes time zone details* will lead to DateTimeException for instances of* TemporalAccessor that do not have time zone information* (such as LocalDateTime and OffsetDateTime).*/private final ZonedDateTime now8 = ZonedDateTime.now();/*** String that can be used by both SimpleDateFormat and* DateTimeFormatter to parse respective date/time instances* from this String.*/private final String dateTimeString = "2014/09/03 13:59:50 MDT";/*** Demonstrate presenting java.util.Date as String matching* provided pattern via use of SimpleDateFormat.*/public void demonstrateSimpleDateFormatFormatting(){final DateFormat format = new SimpleDateFormat(dateTimeFormatPattern);final String nowString = format.format(now);out.println("Date '" + now + "' formatted with SimpleDateFormat and '"+ dateTimeFormatPattern + "': " + nowString);}/*** Demonstrate parsing a java.util.Date from a String* via SimpleDateFormat.*/public void demonstrateSimpleDateFormatParsing(){final DateFormat format = new SimpleDateFormat(dateTimeFormatPattern);try{final Date parsedDate = format.parse(dateTimeString);out.println("'" + dateTimeString + "' is parsed with SimpleDateFormat as " + parsedDate);}// DateFormat.parse(String) throws a checked exceptioncatch (ParseException parseException){out.println("ERROR: Unable to parse date/time String '"+ dateTimeString + "' with pattern '"+ dateTimeFormatPattern + "'.");}}/*** Demonstrate presenting ZonedDateTime as a String matching* provided pattern via DateTimeFormatter and its* ofPattern(String) method.*/public void demonstrateDateTimeFormatFormatting(){final DateTimeFormatter formatter =DateTimeFormatter.ofPattern(dateTimeFormatPattern);final String nowString = formatter.format(now8);out.println(now8 + " formatted with DateTimeFormatter and '"+ dateTimeFormatPattern + "': " + nowString);}/*** Demonstrate parsing ZonedDateTime from provided String* via ZonedDateTime's parse(String, DateTimeFormatter) method.*/public void demonstrateDateTimeFormatParsingTemporalStaticMethod(){final DateTimeFormatter formatter =DateTimeFormatter.ofPattern(dateTimeFormatPattern);final ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateTimeString, formatter);out.println("'" + dateTimeString+ "' is parsed with DateTimeFormatter and ZonedDateTime.parse as "+ zonedDateTime);}/*** Demonstrate parsing ZonedDateTime from String* via DateTimeFormatter.parse(String, TemporaryQuery)* with the Temple Query in this case being ZonedDateTime's* from(TemporalAccessor) used as a Java 8 method reference.*/public void demonstrateDateTimeFormatParsingMethodReference(){final DateTimeFormatter formatter =DateTimeFormatter.ofPattern(dateTimeFormatPattern);final ZonedDateTime zonedDateTime = formatter.parse(dateTimeString, ZonedDateTime::from);out.println("'" + dateTimeString+ "' is parsed with DateTimeFormatter and ZoneDateTime::from as "+ zonedDateTime);}/*** Demonstrate formatting ZonedDateTime via DateTimeFormatter,* but using implementation of Format.*/public void demonstrateDateTimeFormatAndFormatFormatting(){final DateTimeFormatter formatter =DateTimeFormatter.ofPattern(dateTimeFormatPattern);final Format format = formatter.toFormat();final String nowString = format.format(now8);out.println("ZonedDateTime " + now + " formatted with DateTimeFormatter/Format (and "+ format.getClass().getCanonicalName() + ") and '"+ dateTimeFormatPattern + "': " + nowString);}/*** Demonstrate formatting and parsing an instance of Instant.*/public void demonstrateDateTimeFormatFormattingAndParsingInstant(){// Instant instances don't have timezone informationfinal Instant instant = now.toInstant();final DateTimeFormatter formatter =DateTimeFormatter.ofPattern(dateTimeFormatPattern).withZone(ZoneId.systemDefault());final String formattedInstance = formatter.format(instant);out.println("Instant " + instant + " formatted with DateTimeFormatter and '"+ dateTimeFormatPattern + "' to '" + formattedInstance + "'");final Instant instant2 =formatter.parse(formattedInstance, ZonedDateTime::from).toInstant();out.println(formattedInstance + " parsed back to " + instant2);}/*** Demonstrate java.text.SimpleDateFormat and* java.time.format.DateTimeFormatter.** @param arguments Command-line arguments; none anticipated.*/public static void main(final String[] arguments){final DateFormatDemo demo = new DateFormatDemo();out.print("\n1: ");demo.demonstrateSimpleDateFormatFormatting();out.print("\n2: ");demo.demonstrateSimpleDateFormatParsing();out.print("\n3: ");demo.demonstrateDateTimeFormatFormatting();out.print("\n4: ");demo.demonstrateDateTimeFormatParsingTemporalStaticMethod();out.print("\n5: ");demo.demonstrateDateTimeFormatParsingMethodReference();out.print("\n6: ");demo.demonstrateDateTimeFormatAndFormatFormatting();out.print("\n7: ");demo.demonstrateDateTimeFormatFormattingAndParsingInstant();} }下一個屏幕快照中顯示了運行上述演示的輸出。
結(jié)論
與JDK 8之前的版本相比,JDK 8日期/時間類以及相關(guān)的格式和解析類更易于使用。 這篇文章試圖演示如何應(yīng)用這些新類并利用它們的某些優(yōu)點。
翻譯自: https://www.javacodegeeks.com/2014/09/datetime-formattingparsing-java-8-style.html
java 解析日期格式
總結(jié)
以上是生活随笔為你收集整理的java 解析日期格式_日期/时间格式/解析,Java 8样式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 单机游戏《三国:全面战争》有哪位大咖玩过
- 下一篇: 分布式虚拟跟踪