问题描述
我已将SoapUI Pro升级到版本3.3.2,现在我遇到了日期格式问题。 当我运行此代码时:
def startDate = new Date()
def logg = startDate.format("HH:mm:ss.S",TimeZone.getTimeZone('CET'))
此错误引发:
groovy.lang.MissingMethodException:方法的无签名:java.util.Date.format()适用于参数类型:(String,sun.util.calendar.ZoneInfo)值:[HH:mm:ss.S ,sun.util.calendar.ZoneInfo [id =“ CET”,offset = 3600000,dstSavings = 3600000,useDaylight = true,transitions = 137,lastRule = java.util.SimpleTimeZone [id = CET,offset = 3600000,dstSavings = 3600000 ,useDaylight = true,startYear = 0,startMode = 2,startMonth = 2,startDay = -1,startDayOfWeek = 1,startTime = 7200000,startTimeMode = 1,endMode = 2,endMonth = 9,endDay = -1,endDayOfWeek = 1 ,endTime = 7200000,endTimeMode = 1]]]]可能的解决方案:第15行的stream(),toYear(),from(java.time.Instant)错误
我在做什么错了?
解决方法
您应该有权访问java.time
库,该库通常优于java.util.Date
。如果对您的其余工作来说并不太麻烦,我建议您进行切换。
如果必须使用java.util.Date
,则需要使用SimpleDateFormat:
import java.text.SimpleDateFormat
sdf = new SimpleDateFormat("HH:mm:ss.S")
sdf.setTimeZone(TimeZone.getTimeZone("CET"))
println sdf.format(new Date())
==> 06:01:31.299
使用ZonedDateTime
中的java.time
:
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
i = ZonedDateTime.now(ZoneId.of("CET"))
println i.format(DateTimeFormatter.ofPattern("HH:mm:ss.S"))
println i.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))
==> 06:01:31.2
==> 06:01:31.299
请注意,java.time.DateTimeFormatter
中的S
模式已从millisecond
更改为fraction-of-second
个人最清晰的选择是使用java.time.Instant
:
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
println Instant.now()
.atZone(ZoneId.of("CET"))
.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS"))
==> 06:12:22.916