2009-02-03 33 views
1

我想的方法/关闭其工作原理是这样如何使用Groovy显示一段时间?

println TimeDifference.format(System.currentMilliSeconds()-1000*60*60*24*7*6) 

,并打印

1 month, 3 weeks, 2 days, 45 hours and 3 minutes ago. 

有一个现成的解决方案呢?

回答

1

退房this library,它被称为人类的时间,它允许分析和时间是由人类更可消化的渲染。

2

这是一个快速端口。您可以尝试:

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, []) 
0

你也可以检查出使用timeago,这是在JavaScript端完成。那么编写一个taglib是非常容易的,您可以使用它来在标记中使用适当的类创建日期。

相关问题