将时间设置为以hh:mm
格式8:00
传递时间的日期,以下代码按预期工作:
package demo
import static java.util.Calendar.*
class Helper {
public static final Date setTimeToDate(final Date date, final String time) {
Calendar calendar = date.toCalendar()
Integer hourOfDay = time.tokenize(':')[0].toInteger()
calendar.set hourOfDay: hourOfDay, minute: 0, second: 0
calendar.getTime()
}
}
现在我尝试提取将一天中的小时变为自己的方法的逻辑,因此我将代码调整为此要求,如下所示:
package demo
import static java.util.Calendar.*
class Helper {
public static final Date setTimeToDate(final Date date, final String time) {
Calendar calendar = date.toCalendar()
Integer hourOfDay = getHour(time)
calendar.set hourOfDay: hourOfDay, minute: 0, second: 0
calendar.getTime()
}
private Integer getHour(final String time) {
time.tokenize(':')[0].toInteger()
}
}
当我尝试调用setTimeToDate方法时
println Helper.setTimeToDate(new Date(), '8:00')
我收到以下错误
groovy.lang.MissingMethodException: No signature of method: static demo.Helper.getHour() is applicable for argument types: (java.lang.String) values: [8:00]
Possible solutions: getAt(java.lang.String)
at demo.Helper.setTimeToDate(Script1.groovy:9)
at demo.Helper$setTimeToDate.call(Unknown Source)
at demo.Script1.run(Script1.groovy:21)
我特别不理解错误消息[8:00]
答案 0 :(得分:1)
setTimeToDate
是静态的,但getHour
不是,所以没有实例就无法调用它。 <{1}}也是静态的,它可以调用。