Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object HumanTime {
- def formatDuration(seconds: Int): String = {
- var num = Array[Int](0,0,0,0,0)
- var names = Array[String]( "second", "minute", "hour", "day", "year")
- var countNotNull = 0
- if(seconds==0) return "now"
- num(1) = seconds/60
- num(0) =seconds%60
- if(num(0)!=0) countNotNull+=1
- if(num(1)%60>0) countNotNull+=1
- if(num(1)>=60){
- num(2) =num(1)/60
- num(1) %=60
- if(num(2)%24>0) countNotNull+=1
- if(num(2)>=24){
- num(3) =num(2)/24
- num(2) %=24
- if(num(3)%365>0) countNotNull+=1
- if(num(3)>=365){
- num(4) = num(3)/365
- num(3) %= 365
- if(num(4)!=0) countNotNull+=1
- }
- }
- }
- var str =""
- for(i <- 4 to 0 by -1) {
- if(num(i)==0) {
- }
- else{
- if(num(i)>1)
- str+= num(i) + " " + names(i) + "s"
- else if(num(i) == 1)
- str += num(i) + " " + names(i)
- if(countNotNull>2){
- str+= ", "
- countNotNull-=1
- }
- else if (countNotNull==2){
- str+=" and "
- countNotNull-=1
- }
- }
- }
- return str
- }
- }
- ------------------------------------------------------------------------
- object HumanTime {
- def formatDuration(seconds: Int): String =
- (List(("year", 31536000, 100000), ("day", 86400, 365), ("hour", 3600, 24), ("minute", 60, 60), ("second", 1, 60))
- .map {
- case (unit, duration, modulo) => (seconds / duration % modulo, unit)
- }
- .collect {
- case (duration, unit) if duration == 1 => s"$duration $unit"
- case (duration, unit) if duration != 0 => s"$duration ${unit}s"
- })
- match {
- case Nil => "now"
- case List(single) => single
- case list => s"${list.init.mkString(", ")} and ${list.last}"
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement