Binyamin Pekar
Binyamin Pekar

Reputation: 51

Subtract minutes from Date by using Calendar fails

I'm writing an app that must find some time for alarm (from Date object), and then should subtract several hours and minutes (by using Calendar object) selected by the user (interval, several hours and minutes before the selected time).

I tried to do that, and the program subtract the hours (intervalHours below) successfully, but when I'm trying to subtract the minutes (intervalMinutes below), the program shows wrong time.

Here is the code (this.realAlarmTime is the selected time, of Date type):

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(this.realAlarmTime);
            calendar.add(Calendar.HOUR, -(this.intervalHours));
            calendar.add(Calendar.MINUTE, -(this.intervalMinutes));
            this.realAlarmTime = calendar.getTime();

For example, when the program selected the time "15:47", and the interval is 1 MINUTE, the program shows "16:59", while subtracting 1 HOUR shows "14:57"..

is there something wrong in this program, or maybe the function calrnder.add is not correct for this target?

I tried other ways, but did not come up with a solution.

Upvotes: -2

Views: 202

Answers (1)

aled
aled

Reputation: 25872

Assuming you can not change the input Date you can use the current time classes instead of Calendar but the recommendation would be to get rid of Date too. It seems from your question that you might be having an issue related to handling of the timezone. For example if you are assuming the timezone is the local one but the result is in UTC that could be reason the result is not what you are expecting. There is not enough information to be sure.

Example using ZonedDateTime instead of Calendar/Date classes to perform similar calculations:

public class MyClass {
    public static void main(String args[]) {
        int intervalHours=1;
        int intervalMinutes=1;
        ZonedDateTime dateTime = ZonedDateTime.of(2024, 6, 5, 15, 47, 0, 0, ZoneId.of("America/New_York"));
        
        dateTime = dateTime.minusHours(intervalHours);
        dateTime = dateTime.minusMinutes(intervalMinutes);
        System.out.println("Updated date = " + dateTime);
    }
}

Output:

Updated date = 2024-06-05T14:46-04:00[America/New_York]

If you want to use the timezone that your system is using you can use ZoneId.systemDefault() instead of ZoneId.of(). See ZoneId documentation for more options.

Upvotes: 2

Related Questions