3

I'm looking for something in JodaTime or similar which will let me obtain a Duration from a string passed in.

My string will look like: "00:04:23" (HH:MM:SS) I'd like to be able to get that converted to other time units easily.

Unfortunately Duration.parse() from JodaTime doesn't work. Is there another method which would do this, or do I need to roll my own?

As requested some examples:

  • 01:34:22 -> 1 hour 34 minutes and 22 seconds
  • 00:04:23 -> 4 minutes and 23 seconds
  • 00:00:46 -> 46 seconds

It's easy to roll own, but was curious if there was a built in for that, which I was just missing.

2
  • Can you provide some sample inputs and a desired result or output? Commented Feb 8, 2012 at 17:30
  • You mean you want human-readable strings, but ones that can be trivially created using a split, parse, and sprintf? Commented Feb 8, 2012 at 17:43

1 Answer 1

3

I'm still pretty new to JodaTime, but using PeriodFormatterBuilder to obtain a Period and then converting it to a Duration seemed to work for me:

String input = "12:14:02"; ReadWritablePeriod period = new MutablePeriod(); new PeriodFormatterBuilder() .appendHours().appendSeparator(":") .appendMinutes().appendSeparator(":") .appendSeconds().toParser().parseInto(period, input, 0, null); Duration duration = period.toPeriod().toStandardDuration(); 

I'm not sure what the impact of a null Locale is here.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.