Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string HH:MM to Joda Duration?

Tags:

java

jodatime

I have a field in a form to state the time duration of an event. Say, the event is to last 15 mins. So the field will have the following value: 00:15 If it is to last 1 hour: 01:00, etc.

How can I create a Joda-Time Duration object with the string "HH:MM"?

Looking at Joda-Time home page, it mentions that it is possible to create a Duration object from specified object using ConverterManager and DurationConverter respectively.

My question is, how can I implement the above interfaces so that I can create a Duration object by passing the a "4:30" parameter?

Thanks in advance,

Lucas

like image 733
Lucas T Avatar asked Jan 06 '11 20:01

Lucas T


1 Answers

I think a better way would be to use PeriodFormatterBuilder like this:

 PeriodFormatter hoursMinutes= new PeriodFormatterBuilder()
     .appendHours()
     .appendSeparator(":")
     .appendMinutes()
     .toFormatter();

Then you can parse your strings into Period objects and call toStandardDuration() on those - or keep working with the Period, since that seems to match your use case better.

like image 135
Michael Borgwardt Avatar answered Nov 03 '22 06:11

Michael Borgwardt