【问题标题】:What is groovy equivalent to java datetime code什么是 groovy 等价于 java datetime 代码
【发布时间】:2015-03-02 06:32:56
【问题描述】:

工作 java 代码

public static DateTime convertToUTC(String date) throws ParseException {        

    DateTimeParser[] parsers = {
        DateTimeFormat.forPattern( "yyyy-MM-dd" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ssZZ" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSZZ" ).getParser()};

    DateTimeFormatter formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter();


    DateTime dtime = new DateTime(formatter.parseDateTime(date),DateTimeZone.UTC);
    DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
    return formatter.print(dtime );
}

我正在尝试的 Groovy 代码,但是得到了异常,得到了底部给出的异常。

import org.joda.time.format.*
import org.joda.time.DateTimeZone
import org.joda.time.DateTime

def input = message.getInvocationProperty('after').toString()
DateTimeParser[] parsers = [[DateTimeFormat.forPattern( "yyyy-MM-dd" ).getParser()],[DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss" ).getParser()],[DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ssZZ" ).getParser(),DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSZZ" ).getParser()]]
def formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter()
return formatter.print(new DateTime(formatter.parseDateTime(input),DateTimeZone.UTC))

根异常堆栈跟踪: org.codehaus.groovy.runtime.typehandling.GroovyCastException:无法将具有类“java.util.ArrayList”的对象“[org.joda.time.format.DateTimeFormatterBuilder$Composite@755ed6df]”转换为类“org.joda.time”。 format.DateTimeParser' 由于:groovy.lang.GroovyRuntimeException:找不到匹配的构造函数:org.joda.time.format.DateTimeParser(org.joda.time.format.DateTimeFormatterBuilder$Composite)

【问题讨论】:

  • 您可以通过以下方式摆脱大量复制和粘贴代码:def parsers = ["yyyy-MM-dd", ...].collect{ DateTimeFormat.forPattern(it).getParser() }

标签: java groovy


【解决方案1】:
DateTimeParser[] parsers = ...

上面的代码行实际上创建了一个 ArrayList 而不是 Array。试试

def formatter = 
    new DateTimeFormatterBuilder()
    .append( null, parsers.toArray() ).toFormatter()

【讨论】:

  • 他的解析器列表实际上是一个列表列表。不需要围绕日期时间格式化程序构建器的内部 []。
猜你喜欢
  • 2010-10-28
  • 1970-01-01
  • 2015-11-22
  • 2022-09-23
  • 2010-09-21
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多