'Convert int to time format. stop et 24h

I have a TimePickerDialog to choose hours and minutes, then I want to subtract 9 hours from that. Lets say I pick 08:30 then subtract 9 hours from that, then I would get 23:30, but when I code this I get -1:30. I don't get this formatted right. Any tips to new coder in Java?

TimePickerDialog splits hours to time and minutes to minutter.

This is my code now.

arb_tid.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        calendar = Calendar.getInstance();
        currentHour = calendar.get(Calendar.HOUR_OF_DAY);
        currentMinute = calendar.get(Calendar.MINUTE);
        TimePickerDialog timePickerDialog = new TimePickerDialog(kogh.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int timer, int min) {
                time = timer;
                minutter = min;
                arb_tid.setText(String.format(Locale.getDefault(), "%02d:%02d", time, minutter));
            }
        }, currentHour,currentMinute, true);
        timePickerDialog.show();
    }
});


btn_test = findViewById(R.id.btn_test);
btn_test.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (rbtn_9.isChecked()){
            int reds = time - 9 ;
            res_clock.setText(String.format(Locale.getDefault(), "%02d:%02d", reds, minutter));
        }else if (rbtn_11.isChecked()){
            int nors = time - 11;
            res_clock.setText(String.format(Locale.getDefault(), "%02d:%02d", nors, minutter));
        }
    }
});


Solution 1:[1]

tl;dr

LocalTime
.of( 8 , 30 )
.minusHours( 9 )

23:30

Details

You said:

choose hours and minutes, then I want to substract 9 hours from that.

Avoid the terrible legacy date-time classes such as Calendar. They were years ago supplanted by the modern java.time classes defined in JSR 310.

For time-of-day, use LocalTime. This class represents a generic 24-hour clock. Be aware that some dates in some time zones are not 24-hours long.

LocalTime lt = LocalTime.of( myHour , myMinute ) ;
LocalTime earlier = lt.minusHours( 9 ) ;

You said:

lets say I pick 08:30 then substract 9 hours from that, then i would get 23:30,

Alternatively, you can use Duration to represent the amount of time to add or subtract.

LocalTime.of( 8 , 30 ).minus( Duration.ofHours( 9 ) )

See this code run live at IdeOne.com.

23:30

To generate text representing the value of the LocalTime object in a format other than ISO 8601, use DateTimeFormatter.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1