关于java: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中解决了该问题,并且以下日期操作可以正常工作:

1
?today = new Date()+90;today.format('yyyy-MM-dd HH:mm:ss.S');

结果:2019-12-02 08:07:15.294

在Groovy 2.5.4中,相同的表达式引发此异常:

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沙箱"中重现此行为:

在这里可以正常工作:groovy-playground(版本2.4.1.5)
在此失败:groovyconsole(版本2.5.7)

在这种情况下,有什么可行的替代方法? 我已经阅读了有关新的Date API的信息,但是找不到有关如何使用日期处理(例如+ 90天)的详细信息。


我同意Ole V.V.关于使用新的日期/时间API的建议。 这是您如何以更具Groovy风格编写他的Java示例的方法。

1
2
3
4
5
6
7
8
9
// 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')

看看TimeCategory

1
2
import groovy.time.TimeCategory
def theDate = use(TimeCategory){new Date() + 90.days}.format('yyyy-MM-dd HH:mm:ss.S')


尽管Groovy为旧的Java Date类添加了进一步的支持,但我仍然认为您不应该使用它。 它总是设计不当,现在已经过时了。 而是使用java.time(现代的Java日期和时间API)。 很抱歉,我将不得不信任您从Java代码进行翻译。

1
2
3
4
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.S");
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Africa/Bamako"));
    ZonedDateTime in90Days = now.plusDays(90);
    System.out.println(in90Days.format(formatter));

刚运行时的输出为:

2020-01-01 08:37:13.3

如果不是非洲/巴马科,请替换您所需的时区。

链接:Oracle教程:Date Time解释了如何使用java.time。