简体   繁体   中英

Dynamic C, How to add 2 “hours” as 4 digit Integer

I need to know how can I add 2 "hours" as integer? It is 24-h format

int add2Hours(int _time1,int _time2)
{ 
} 

sample: 13:45 is: (hhmm) 1345

1345 + 30 returns 1415

Your time is in hhmm format, separate the hh and mm part. Then add the parts separately.

int add2hours(int _time1, int _time2)
{
    int hh1, hh2, mm1, mm2;
    int rHH,rMM, res;
    hh1 = _time1/100;
    hh2 = _time2/100;
    mm1 = _time1 % 100;
    mm2 = _time2 % 100;
    rMM = mm1 + mm2;
    rHH = rMM/60;
    rMM = rMM % 60;
    rHH = rHH + hh1 + hh2;
    res = rHH*100 + rMM;
    return res;
}

NOTE: This will not handle any time greater than 24hrs. eg if the inputs are 2345 and 30, the output will be 2415 instead of 15(0015). You have to handle it if you need.

If the function for adding time is declared as follows,

int add2Hours(int _time1,int _time2);

and the syntax of passing time is as follows,

hhmm (For example 2230)

Then you can add the times as follow,

temp1= _time1;
temp2= _time2;

m1 = temp1 % 100;
m2 = temp2 % 100;

h1 = temp1 / 100;
h2 = temp2 / 100;

m3 = m1 + m2;

m3 > 59 ? m3=m3%60, h3=1 : h3=0;

h3 = h1 + h2 + h3;

h3 > 23 ? h3=h3%24, d=1 : d=0; /* If more than 23 hours */

printf("\nThe time is %d-%d-%d",d,h3,m3);   

First convert the time to a common domain(sec/millisec...). Then add and make the result to the required format.

  • Add the hours together. 13 + 0.
  • Get the minutes of each time by subtracting the time with the time/100*100. Note that integer arithmetic in C truncates. Example:

m = time - (time/100*100)

m = 1345 - (1345/100*100)

m = 1345 - (13*100)

m = 1345 - 1300

m = 45

  • Add the minutes together. 45 + 30 = 75.
  • Add "the minute sum/60" hours to the result. Ie 75/60 = 1.
  • Then add "the minute sum modulo 60" minutes to the same result. Ie 75%60 = 15.

How about this?

int add2Hours(int _time1,int _time2)
{
    int minutes = (_time1%100 + _time2%100)
    int time = (((minutes/60)+(_time1/100 + _time2/100))%24)*100 + minutes%60;
    return time;
}

Thanks guys... here is my function!

int Add2Times (int _time1, int _time2)
{
    int hour = _time1 / 100 + _time2 / 100;
    int min = _time1 % 100 + _time2 % 100;

    hour += min / 60;
    min = min % 60;


    hour = hour % 24;

    return hour * 100 + min;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM