PiBurner
PiBurner

Reputation: 75

adding minutes using a formatted string in java or joda time

I'm trying to add a string representation of time in minutes (4:30) to another string (10:00:00) like you would say 'ten o'clock plus 4 minutes, 30 seconds.

If I sound a bit verbose, it's because I've spent 7 hrs searching the web for an answer and keep getting how to convert a fixed string of even minutes to date/time.

I tried to use joda time but can't figure out how to make 4:30 into an integer (I can make it work with'04'). These times are strings in code from variables, not something the user enters at the command line. I'm using JDK 1.7 and netbeans 8.

Upvotes: 1

Views: 794

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

Java 8 Time API

You could take advantage of Java 8's new Time API, which is similar to JodaTime

The first thing you need is a Duration, something like...

Duration d = Duration.parse("PT0H4M30S");

or

Duration d = Duration.ofMinutes(4).plusSeconds(30);

Next, you need to generate a LocalTime value

LocalTime time = LocalTime.parse("10:00:00", DateTimeFormatter.ofPattern("HH:mm:ss"));

and then you can simply add the Duration to it

time = time.plus(d);

which will result in a value of

10:04:30

The difficult part is getting the values of the duration from the String, but if you can guarantee the format, you could simply use String#split

JodaTime

JodaTime would make it slightly easier, for example, you can parse 4:30 into a Period using something like...

PeriodFormatter formatter = new PeriodFormatterBuilder()
        .appendMinutes().appendSuffix(":")
        .appendSeconds()
        .toFormatter();
Period p = formatter.parsePeriod("4:30");

Then you could simply parse 10:00:00 into a LocalTime and add the Period

LocalTime lt = LocalTime.parse("10:00:00", DateTimeFormat.forPattern("HH:mm:ss"));
lt = lt.plus(p);
System.out.println(lt);

which outputs...

10:04:30.000

Upvotes: 4

Related Questions