Groovy里的日期处理
生活随笔
收集整理的這篇文章主要介紹了
Groovy里的日期处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Groovy官網的文檔:
http://www.groovy-lang.org/groovy-dev-kit.html
package jerry;def date = LocalDate.parse('Jun 3, 04', 'MMM d, yy') assert date == LocalDate.of(2004, Month.JUNE, 3)def time = LocalTime.parse('4:45', 'H:mm') assert time == LocalTime.of(4, 45, 0)def offsetTime = OffsetTime.parse('09:47:51-1234', 'HH:mm:ssZ') assert offsetTime == OffsetTime.of(9, 47, 51, 0, ZoneOffset.ofHoursMinutes(-12, -34))def dateTime = ZonedDateTime.parse('2017/07/11 9:47PM Pacific Standard Time', 'yyyy/MM/dd h:mma zzzz') assert dateTime == ZonedDateTime.of(LocalDate.of(2017, 7, 11),LocalTime.of(21, 47, 0),ZoneId.of('America/Los_Angeles') )println 'time check done!'這段代碼無法直接執行,報錯誤消息:
Caught: groovy.lang.MissingPropertyException: No such property: LocalDate for class: jerry.helloWorld groovy.lang.MissingPropertyException: No such property: LocalDate for class: jerry.helloWorldat jerry.helloWorld.run(helloWorld.groovy:3)at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)http://docs.groovy-lang.org/latest/html/groovy-jdk/java/time/package-summary.html
需要先導入java.time包:
如下圖,導入java.time.*之后,Eclipse里的LocalDate,LocalTime都高亮顯示了:
官網的代碼無法直接運行,需要把所有parse方法的第二個參數,即字符串類型的format:
def date = LocalDate.parse(‘Jun 3, 04’, ‘MMM d, yy’)
全部替換成用方法DateTimeFormatter.ofPattern返回:
package jerry;import java.time.* import java.time.format.DateTimeFormatterCharSequence sequence = 'Jun 3, 04'; java.time.format.DateTimeFormatter formatter = DateTimeFormatter.ofPattern('MMM d, yy');def date = LocalDate.parse(sequence, formatter)println( "formatted: " + date.toString())assert date == LocalDate.of(2004, Month.JUNE, 3)def time = LocalTime.parse('4:45', DateTimeFormatter.ofPattern('H:mm')) assert time == LocalTime.of(4, 45, 0)def offsetTime = OffsetTime.parse('09:47:51-1234', DateTimeFormatter.ofPattern('HH:mm:ssZ')) assert offsetTime == OffsetTime.of(9, 47, 51, 0, ZoneOffset.ofHoursMinutes(-12, -34))def dateTime = ZonedDateTime.parse('2017/07/11 9:47PM Pacific Standard Time', DateTimeFormatter.ofPattern('yyyy/MM/dd h:mma zzzz')) assert dateTime == ZonedDateTime.of(LocalDate.of(2017, 7, 11),LocalTime.of(21, 47, 0),ZoneId.of('America/Los_Angeles') )println 'time check done!'修改后的代碼如下:
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的Groovy里的日期处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 京东 31 亿元北京拿地规划图曝光:员工
- 下一篇: 英伟达推出“护栏”软件,让 AI 聊天机