【发布时间】: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() }