Chunelle
Chunelle

Reputation: 27

How to add time in C?

Essentially the program I've made adds time when the times are listed in the kind of military format (eg. 2300 is equal to 11pm) and then a duration is added (eg. 345, 3 hours 45 minutes.)

I've come across an issue in that when you add time to something that surpasses midnight it will continue to add past that. So for instance if you add 2 hours (200) to 11pm (2300) you will get a result of 2500 which is illogical for this purpose.

What I need my program to do is reach 2400 (midnight) and then reset to 0 but continue to add the remaining amount that needed to be added.

I've been trying to figure this out but I cannot figure out how I'm going to make it add what remains after you reset it to 0.

Upvotes: 1

Views: 3935

Answers (3)

chux
chux

Reputation: 153338

  1. Break 24 hour/minute encode as a 4-digit int into hours and minutes. Avoid assuming values are in their primary range.

  2. Add

  3. Re-form time into the primary range.

Example

typedef struct {
  int hour;    // Normal range 0 - 23
  int minute;  // Normal range 0 - 59
} hhmm;

hhmm int_to_hhmm(int src) {
  src %= 2400;
  if (src < 0) src += 2400;
  hhmm dest = { src / 100, src % 100 };
  return dest;
}

int hhmm_to_int(hhmm src) {
  src.hour += src.minute / 60;
  src.minute %= 60;
  if (src.minute < 0) {
    src.minute += 60;
    src.hour--;
  }
  src.hour %= 24;
  if (src.hour < 0) {
    src.hour += 24;
  }
  return src.hour * 100 + src.minute;
}

int add_mill_format_times(int t0, int t1) {
  hhmm hhmm0 = int_to_hhmm(t0);
  hhmm hhmm1 = int_to_hhmm(t1);
  hhmm sum = { hhmm0.hour + hhmm1.hour, hhmm0.minute + hhmm1.minute };
  return hhmm_to_int(sum);
}

Upvotes: 1

molbdnilo
molbdnilo

Reputation: 66371

Since minutes are added modulo 60 and hours modulo 24, you need to handle them separately.

Something like

int add_time(int old_time, int addition)
{
    /* Calculate minutes */
    int total_minutes = (old_time % 100) + (addition % 100);
    int new_minutes = total_minutes % 60;
    /* Calculate hours, adding in the "carry hour" if it exists */
    int additional_hours = addition / 100 + total_minutes / 60;
    int new_hours = (old_time / 100 + additional_hours) % 24;
    /* Put minutes and hours together */ 
    return new_hours * 100 + new_minutes; 
}

Upvotes: 2

awadhesh14
awadhesh14

Reputation: 89

you can do

addTime(int time1,int time2{
int first,last,addH,addM
last = func1(time1) + func2(time2);
last=last1+last2;
if(last > 60){
    addH=last/60;
    addM=last%60;
}
first=func2(time1)+func2(time2);
first+= addH;
last += addM;
first/=24;
return first*100 + addM;
}

func2(int time){
int i;
for(i=0;i<2;i++)
    time/=10;
return time;
}

func1(int time){
int l=time%10;
time/=10;
int m=time%10;
return m*10 + l;
}

Upvotes: 0

Related Questions