Date.plus 在 2.5.4 Groovy Runtime 中不起作用,有什么替代方法吗?

我们想要在当前日期中添加天数并以特定方式对其进行格式化。这个问题在 Groovy 2.4.13 中得到了解决,并且以下日期操作工作正常:

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:没有方法签名:java.util.Date.plus() 适用于参数类型:(整数)值:[90] 可能的解决方案: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 sandboxes”中重现此行为:

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

在这种情况下,可行的替代方案是什么?我读过有关新的 Date API 的信息,但找不到有关如何使用它的详细信息,以及日期操作(例如 + 90 天)。


慕尼黑5688855
浏览 88回答 4
4回答

qq_花开花谢_0

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

千万里不及你

以下是您如何以更 Groovy 风格编写 Java 示例。// 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 overloadedZonedDateTime in90Days = now + 90// you can pass a String to format without needed a full DateTimeFormatter instanceprintln in90Days.format('uuuu-MM-dd HH:mm:ss.S')

倚天杖

虽然 Groovy 为旧的 JavaDate类添加了一些进一步的支持,但我仍然认为您不应该使用它。它的设计一直很糟糕,现在已经过时了。请改用现代 Java 日期和时间 API java.time。很抱歉,我必须信任您来翻译 Java 代码。    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如果不是非洲/巴马科,请替换您所需的时区。

LEATH

您可以使用日历来实现这一点&nbsp; &nbsp; Calendar cal = new GregorianCalendar();&nbsp; &nbsp; cal.add(Calendar.DATE, 90);&nbsp; &nbsp; Date date = cal.getTime();所有步骤必须分开,不能在一行中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java