Scott
Scott

Reputation: 9488

Java Timing Library

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:

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

Upvotes: 3

Views: 140

Answers (1)

Mark Peters
Mark Peters

Reputation: 81074

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.

Upvotes: 3

Related Questions