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

前端 未结 19 1555
情话喂你
情话喂你 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条回答
  •  梦毁少年i
    2020-11-22 04:24

    In Scala, building up on YourBestBet's solution but simplified:

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

提交回复
热议问题