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.helloWorld
	at 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.DateTimeFormatter

CharSequence 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的原创文章,请关注公众号"汪子熙":

汪子熙 CSDN认证博客专家 前端框架 Node.js SAP
Jerry Wang,2007 年从电子科技大学计算机专业硕士毕业后加入 SAP 成都研究院工作至今。Jerry 是 SAP 社区导师,SAP 中国技术大使。14 多年的 SAP 产品开发生涯,Jerry 曾经先后参与 SAP Business ByDesign,SAP CRM,SAP Cloud for Customer,SAP S/4HANA,SAP Commerce Cloud(电商云)等标准产品的研发工作。
相关推荐
©️2020 CSDN 皮肤主题: 博客之星2020 设计师:CY__ 返回首页
实付 49.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值