如何在Java中格式化时间?(例如,格式为H:MM:SS)

229

我想使用“H:MM:SS”这样的格式来格式化以秒为单位的时间段。目前Java中的实用工具是设计用来格式化时间而不是持续时间。

22个回答

-4
在Scala中,基于YourBestBet的解决方案但简化:
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

OP要求在Java中格式化以秒为单位的持续时间的解决方案。 - maxxyme

-5

在 Scala 中,不需要任何库:

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("")

5
这不是Scala的一个好广告吧?虽然不需要库,但却需要写同样数量的代码...? - Adam
我喜欢递归的方法,但它可以被大大简化:https://dev59.com/c3VC5IYBdhLWcg3whRgw#52992235 - dpoetzsch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接