Advertisement
sleepwalker7

Human readable duration format

Apr 24th, 2020
643
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.85 KB | None | 0 0
  1. object HumanTime {
  2.  
  3.     def formatDuration(seconds: Int): String = {
  4.     var num = Array[Int](0,0,0,0,0)
  5.     var names = Array[String]( "second", "minute", "hour", "day", "year")
  6.     var countNotNull = 0
  7.  
  8.     if(seconds==0) return "now"
  9.  
  10.     num(1) = seconds/60
  11.     num(0) =seconds%60
  12.     if(num(0)!=0) countNotNull+=1
  13.     if(num(1)%60>0) countNotNull+=1
  14.     if(num(1)>=60){
  15.       num(2) =num(1)/60
  16.       num(1) %=60
  17.       if(num(2)%24>0) countNotNull+=1
  18.       if(num(2)>=24){
  19.         num(3) =num(2)/24
  20.         num(2) %=24
  21.         if(num(3)%365>0) countNotNull+=1
  22.         if(num(3)>=365){
  23.           num(4) = num(3)/365
  24.           num(3) %= 365
  25.           if(num(4)!=0) countNotNull+=1
  26.         }
  27.       }
  28.     }
  29.     var str =""
  30.     for(i <- 4 to 0 by -1) {
  31.       if(num(i)==0) {
  32.       }
  33.       else{
  34.         if(num(i)>1)
  35.           str+= num(i) + " " + names(i) + "s"
  36.         else if(num(i) == 1)
  37.           str += num(i) + " " + names(i)
  38.         if(countNotNull>2){
  39.           str+= ", "
  40.           countNotNull-=1
  41.         }
  42.         else if (countNotNull==2){
  43.           str+=" and "
  44.           countNotNull-=1
  45.         }
  46.       }
  47.     }
  48.     return str
  49.   }
  50.    
  51. }
  52.  
  53. ------------------------------------------------------------------------
  54.  
  55. object HumanTime {
  56.  
  57.   def formatDuration(seconds: Int): String =
  58.     (List(("year", 31536000, 100000), ("day", 86400, 365), ("hour", 3600, 24), ("minute", 60, 60), ("second", 1, 60))
  59.       .map {
  60.         case (unit, duration, modulo) => (seconds / duration % modulo, unit)
  61.       }
  62.       .collect {
  63.         case (duration, unit) if duration == 1 => s"$duration $unit"
  64.         case (duration, unit) if duration != 0 => s"$duration ${unit}s"
  65.       })
  66.       match {
  67.         case Nil => "now"
  68.         case List(single) => single
  69.         case list => s"${list.init.mkString(", ")} and ${list.last}"
  70.       }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement