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.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
My library Time4J offers a pattern-based solution (similar to
Apache DurationFormatUtils
, but more flexible):This code demonstrates the capabilities to handle hour overflow and sign handling, see also the API of duration-formatter based on pattern.
in scala, no library needed:
This might be kind of hacky, but it is a good solution if one is bent on accomplishing this using Java 8's
java.time
:This is going to be one of the new features in java 7
JSR-310
If you're using a version of Java prior to 8... you can use Joda Time and
PeriodFormatter
. If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be usingDuration
for the most part - you can then calltoPeriod
(specifying whateverPeriodType
you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get aPeriod
which you can format.If you're using Java 8 or later: I'd normally suggest using
java.time.Duration
to represent the duration. You can then callgetSeconds()
or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a single negative sign in the output string. So something like:Formatting this way is reasonably simple, if annoyingly manual. For parsing it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.