JodaTime - Adding/Subtracting Hours and minutes to time, only minutes are being added/subtracted correctly?

StackOverflow https://stackoverflow.com/questions/14336771

  •  15-01-2022
  •  | 
  •  

Question

In a bit of a problem. I have a onClick that when clicked will get the current time and add a certain number of hours and minutes. The code below is what I have and it currently sends the data to another Activity and displays it, except it doesn't change the hours.

public void onClickHere (View v) {

    String ti1me, ti2me, ti3me;

    //carry out calculation
    LocalTime localtime = new LocalTime();
    LocalTime dt = new LocalTime(localtime);

        //Add two hours and subtract 10 minutes
        LocalTime twoHoursLater = dt.plusHours(2);
                  twoHoursLater = dt.minusMinutes(10);

        //Add three hours and 9 minutes
        LocalTime threeHoursLater = dt.plusHours(3);
                  threeHoursLater = dt.plusMinutes(9);

        //Add five hours and subtract 8 minutes
        LocalTime fiveHoursLater = dt.plusHours(5);
                  fiveHoursLater = dt.minusMinutes(8);


    DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
    ti1me = (twoHoursLater.toString(formatter));
    ti2me = (threeHoursLater.toString(formatter));
    ti3me = (fiveHoursLater.toString(formatter));

    Intent i = new Intent(this, WakeUpMain.class);
    i.putExtra("time1", ti1me);
    i.putExtra("time2", ti2me);
    i.putExtra("time3", ti3me);
    startActivity(i);

}

As you can see I'm trying to get three times, and adding various minutes and hours to both, the minutes add fine but the hour stays with the current time, or changes based on how the minutes are added and whether it carries into the next hour.

It's 11:22 as I type this and if I run the app and click the button the outputs are:
11:11
11:31
11:14

The hours aren't changing. Is there a way to fix this? The hour only changes when for example the time is 11:05, the first time would then show up as 10:55.

Would appreciate any help. Really confusing me.

Was it helpful?

Solution

When you adding minutes you flush your hours increment:

twoHoursLater = dt.minusMinutes(10);

Use

LocalTime twoHoursLater = dt.minusMinutes(10);
    twoHoursLater = twoHoursLater.plusHours(2);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top