Date.plus在2.5.4 Groovy Runtime中不起作用,替代方法是什么? [英] Date.plus not working in 2.5.4 Groovy Runtime, what is the alternative?
问题描述
我们要在当前日期中添加天数,并以特定方式设置其格式.在Groovy 2.4.13中解决了该问题,并且以下日期操作可以正常工作:
We want to add days to the current date and format it in a specific way. This was solved in Groovy 2.4.13 and the following date manipulation works fine:
today = new Date()+90;today.format('yyyy-MM-dd HH:mm:ss.S');
结果:2019-12-02 08:07:15.294
Result: 2019-12-02 08:07:15.294
在Groovy 2.5.4中,相同的表达式引发此异常:
In Groovy 2.5.4 the same expression throws this exception:
groovy.lang.MissingMethodException:没有方法的签名:java.util.Date.plus()适用于参数类型:(整数)值:[90]可能的解决方案:parse(java.lang.String),split(groovy.lang.Closure),use([Ljava.lang.Object;),is(java.lang.Object),wait(),clone()在Script1.run(Script1.groovy:3)
groovy.lang.MissingMethodException: No signature of method: java.util.Date.plus() is applicable for argument types: (Integer) values: [90] Possible solutions: parse(java.lang.String), split(groovy.lang.Closure), use([Ljava.lang.Object;), is(java.lang.Object), wait(), clone() at Script1.run(Script1.groovy:3)
我能够在线上在"Groovy沙箱"中重现这种行为:
I was able to reproduce this behaviour in "Groovy sandboxes" online:
在这里工作正常: groovy-操场(版本2.4.1.5)在此失败: groovyconsole (版本2.5.7)
Working fine here: groovy-playground (Version 2.4.1.5) Failing here: groovyconsole (Version 2.5.7)
在这种情况下,可行的替代方法是什么?我已经阅读了有关新的Date API的信息,但是找不到有关如何通过日期操作(例如+ 90天)使用它的详细信息.
What is the working alternative in this case? I have read about a new Date API, but couldn't find the details about how to use it, with date manipulation (+ 90 days for example).
推荐答案
我同意Ole V.V.关于使用新的日期/时间API的建议.这是您如何以更具Groovy风格编写他的Java示例的方法.
I agree with Ole V.V.'s recommendations to use the new Date/Time API. Here is how you would write his Java sample in a more Groovy style.
// you can assemble aggregate types by left shifting the aggregates
// I'm not endorsing this approach, necessarily, just pointing it out as an alternative
ZonedDateTime now = LocalDate.now() << LocalTime.now() << ZoneId.of('Africa/Bamako')
// the plus operator is overloaded
ZonedDateTime in90Days = now + 90
// you can pass a String to format without needed a full DateTimeFormatter instance
println in90Days.format('uuuu-MM-dd HH:mm:ss.S')
这篇关于Date.plus在2.5.4 Groovy Runtime中不起作用,替代方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!