日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

日期/时间格式/解析,Java 8样式

發(fā)布時間:2023/12/3 java 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 日期/时间格式/解析,Java 8样式 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

自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教程在“ 格式化”課程 ( Dates and Times )中介紹了這些java.util和java.text類。 Java教程中新的Date Time軌跡涵蓋了Java 8中有關(guān)日期和時間的新類,以及它們的格式和解析 。 這篇文章提供了一些實際的例子。

在通過示例演示Java 8樣式的日期/時間解析/格式化之前,先比較一下DateFormat / SimpleDateFormat和DateTimeFormatter的Javadoc描述。 下表包含可從Javadoc的比較中直接或間接搜集到的每種區(qū)分格式信息的區(qū)分信息。 從此表中可能最重要的觀察結(jié)果是,新的DateTimeFormatter是線程安全的且不可變的,并且DateTimeFormatter提供了用于解析和格式化日期和時間的API的概述。

特性 DateFormat / SimpleDateFormat DateTimeFormatter
目的 “以與語言無關(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); }

根據(jù)模式從字符串中解析日期/時間類很容易完成。 有兩種方法可以實現(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中引入的新日期/時間類聯(lián)系起來的類很有幫助。這方面的一個示例是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

總結(jié)

以上是生活随笔為你收集整理的日期/时间格式/解析,Java 8样式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。