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

前端 未结 19 1941
情话喂你
情话喂你 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:15

    In scala (I saw some other attempts, and wasn't impressed):

    def formatDuration(duration: Duration): String = {
      import duration._ // get access to all the members ;)
      f"$toDaysPart $toHoursPart%02d:$toMinutesPart%02d:$toSecondsPart%02d:$toMillisPart%03d"
    }
    

    Looks horrible yes? Well that's why we use IDEs to write this stuff so that the method calls ($toHoursPart etc) are a different color.

    The f"..." is a printf/String.format style string interpolator (which is what allows the $ code injection to work) Given an output of 1 14:06:32.583, the f interpolated string would be equivalent to String.format("1 %02d:%02d:%02d.%03d", 14, 6, 32, 583)

提交回复
热议问题