How to format a duration in java? (e.g format H:MM:SS)

前端 未结 19 1535
情话喂你
情话喂你 2020-11-22 03:32

I\'d like to format a duration in seconds using a pattern like H:MM:SS. The current utilities in java are designed to format a time but not a duration.

19条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 04:13

    in scala, no library needed:

    def prettyDuration(str:List[String],seconds:Long):List[String]={
      seconds match {
        case t if t < 60 => str:::List(s"${t} seconds")
        case t if (t >= 60 && t< 3600 ) => List(s"${t / 60} minutes"):::prettyDuration(str, t%60)
        case t if (t >= 3600 && t< 3600*24 ) => List(s"${t / 3600} hours"):::prettyDuration(str, t%3600)
        case t if (t>= 3600*24 ) => List(s"${t / (3600*24)} days"):::prettyDuration(str, t%(3600*24))
      }
    }
    val dur = prettyDuration(List.empty[String], 12345).mkString("")
    

提交回复
热议问题