我想要一个像这样工作的方法/闭包
println TimeDifference.format( System.currentMilliSeconds()-1000*60*60*24*7*6 )
并打印
1 month, 3 weeks, 2 days, 45 hours and 3 minutes ago.
这是否有现成的解决方案?
答案 0 :(得分:3)
这是一个快速端口。你可以试试:
def distance_of_time_in_words = { fromTime, toTime, includeSeconds, options ->
if(toTime==null) toTime = 0
if(includeSeconds==null) includeSeconds = false
if(options==null) options = []
def distance_in_mins = (int)Math.round(Math.abs(toTime - fromTime)/60.0)
def distance_in_seconds = (int)Math.round(Math.abs(toTime - fromTime))
switch (distance_in_mins) {
case 0..1:
if(distance_in_mins == 0) {
return "less than 1 minute"
} else {
if (includeSeconds == false) return "${distance_in_mins} minute"
}
switch (distance_in_seconds) {
case 0..4: return "less than 5 seconds"
case 5..9: return "less than 10 seconds"
case 10..19: return "less than 20 seconds"
case 20..39: return "half a minute"
case 40..59: return "less than 1 minute"
default: return "1 minute"
}
case 2..44: return "${distance_in_mins} minutes"
case 45..89: return "about an hour"
case 90..1439: return "about ${Math.round(distance_in_mins / 60.0)} hours"
case 1440..2879: return "a day"
case 2880..43199: return "${Math.round(distance_in_mins / 1440)} days"
case 43200..86399: return "a month"
case 86400..525599: return "${Math.round(distance_in_mins / 43200)} months"
case 525600..1051199: return "a year"
default: return "over ${Math.round(distance_in_mins / 525600)} years"
}
}
def d = new Date().time
println distance_of_time_in_words(d, d + 10, true, [])
println distance_of_time_in_words(d, d + 60, true, [])
println distance_of_time_in_words(d, d + 35, true, [])
println distance_of_time_in_words(d, d + 123, true, [])
println distance_of_time_in_words(d, d + 400, true, [])
println distance_of_time_in_words(d, d + 1300*60, true, [])
println distance_of_time_in_words(d, d + 2000*60, true, [])
println distance_of_time_in_words(d, d + 3.5*60*60*24, true, [])
println distance_of_time_in_words(d, d + 32*60*60*24, true, [])
println distance_of_time_in_words(d, d + 65*60*60*24, true, [])
println distance_of_time_in_words(d, d + 1.5*12*30*60*60*24, true, [])
println distance_of_time_in_words(d, d + 7*12*30*60*60*24, true, [])
答案 1 :(得分:1)
查看this library,它称为人类时间,它允许解析和渲染人类更容易消化的时间。
答案 2 :(得分:0)
我不知道Groovy,但是移植the one from rails非常简单。 您可以通过单击“show source”来查看Ruby源代码。
答案 3 :(得分:0)
您可以使用此PrettyDate插件 - http://www.grails.org/plugin/pretty-date
或此PrettyTime插件 - http://www.grails.org/plugin/pretty-time
答案 4 :(得分:0)
您还可以使用timeago结帐,这是在javascript端完成的。编写一个taglib非常容易,您可以使用它来在标记中使用适当的类创建日期。
答案 5 :(得分:0)
我使用joda-time插件,Period和PeriodFormatter,例如here。