RED_
RED_

Reputation: 3007

Carrying out time calculations with Joda-time?

I'm stuck on this task. I want to add various hours or minutes to the current time. So the user presses a button and the onClick will pull the current time and then add however many hours and minutes I decide. At the moment I have it adding two hours but I want to be able to add and subtracts around 2 hours and 14 minutes.

Here is what I have so far:

public void onClickHere (View v) {

    LocalTime localtime = new LocalTime();
    LocalTime dt = new LocalTime(localtime.getHourOfDay(), localtime.getMinuteOfHour());
    LocalTime twoHoursLater = dt.plusHours(2);

    Text1.setText("Time: " + twoHoursLater);

}

Now the code above does part of what I want. It gets the localtime and adds two hours to it. However it shows a lot of extra numbers. Seconds & Milliseconds.

Is there a way for me to only show the hours and minutes?

By calling getHourOfDay() and getMinuteOfHour() it only pulls the hours and minutes BUT it still shows 00.000 for the seconds and minutes.

So if I pressed the button now it would show 10:58:00.000. What I would like it to show is 10:58.

and Eventually being able to add minutes but I think that's another issue, a simpler issue that I can simply take example from already knowing how to add two hours.

Hopefully I've explained this well enough.

Upvotes: 3

Views: 125

Answers (1)

assylias
assylias

Reputation: 328608

You need to use a DateTimeFormatter, for example:

DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
Text1.setText("Time: " + twoHoursLater.toString(formatter));

Note: DateTimeFormatter is thread safe so you can define it as a private final static variable and reuse it instead of creating one instance every time onClickHere is called.

Upvotes: 3

Related Questions