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.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 usingDurationfor the most part – you can then calltoPeriod(specifying whateverPeriodTypeyou want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get aPeriodwhich you can format.If you’re using Java 8 or later: I’d normally suggest using
java.time.Durationto 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.