I am trying to write a code that calculates the end time of an event (in military time) based on 6 values the user enters: the starting hours, minutes, and seconds, and the duration hours, minutes and seconds.
The user can't enter values greater than 24, 60, and 60 for hours, minutes, and seconds, respectively, and they can't enter a negative number either. That part of the code I have working fine, but I'm having trouble computing the end time of the event. I can get it to work in some cases, but sometimes I get a negative value for seconds.
This is what I have:
// Compute ending time.
endHour = startHours + durationHours ;
endMinutes = startMinutes + durationMinutes ;
endSeconds = startSeconds + durationSeconds ;
// Convert seconds to minutes (etc.) or convert hours if it runs into the next day
while (endHour >= 24 || endMinutes >= 60 || endSeconds >= 60)
{
if (endSeconds >= 60)
endMinutes = endMinutes + 1;
endSeconds = endSeconds - 60;
if (endMinutes >= 60)
endHour = endHour + 1;
endMinutes = endMinutes - 60 ;
if (endHour >= 24)
endHour = endHour - 24;
}
I was thinking of doing another while loop for if it comes out negative, but I'm not sure if there's some other general problem or if there's a more efficient way to go about it. Any help would be appreciated! :)