We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
I wan to find the time difference between Current time and the Previous time.
In my project i maintain some time interval and that interval is checked by converting the both previous and current time to entire seconds and find the difference.
The difference is checked with the interval in the program.
I have written the program to find the difference but for example let me say my previous time - 23:59:30 and the current time is - 00:00:54 then when i try to find the difference like, time = current time - previous time i get some wrong value due to overflow.
Bcos the each second the previous and current time is converted to total seconds and its difference is only checked.
can any suggest me how this can be rectifed?
void Time_Secs_Calculation(void) { Temp_1 = Hex2Dec(ch[2]); //DECIMAL VALUE of hr Temp_2 = Hex2Dec(ch[1]); //decimal value of min Temp_3 = Hex2Dec(ch[0]); //decimal value of sec if((Temp_1 == 0) && (Temp_2 == 0) && (Temp_3 == 0)) { Temp_1 = 23; Temp_2 = 60; } Time_1 = (((unsigned long int)(Temp_1)*60*60) + ((unsigned long int)(Temp_2)*60) + (unsigned long int)(Temp_3)); //GET THE TOTAL CURRENT TIME interms of sec Time_2 = (((unsigned long int)(Prev_Hr)*60*60) + ((unsigned long int)(Prev_Min)*60) + (unsigned long int)(Prev_Sec)); //GET THE PREVIOUS TIME interms of sec Time = Time_1 - Time_2; //DIFFERENCE TIME = CURRENT // TIME - PREVIOUS TIME SBUF=' '; printf("\n Time diff is %lu",Time); TI = 0; Delay(1000); Temp = ((unsigned int)(Time) / 60); //GET THE QUOTIENT TO GET MINUTES AND HOUR Diff_Hr = (Temp / 60); //GET THE DIFFERENCE OF HOURS Diff_Min = (Temp % 60); //GET THE DIFFERENCE OF mins Diff_Sec = (Time % 60); //GET THE DIFFERENCE OF secs intSec_Diff = ((Diff_Min*60) + Diff_Sec); return; }
this is my coding.
the probelm comes when the previous time and current time are said as abopve already since the variable,
intSec_Diff is the variable maintaining the interval between previous and current time in terms of seconds.
Your problem is because you have only time and not date; therefore, you have to assume that the date must have changed if the times are in the "wrong order"
if( current_time >= previous_time ) { // both times are from the same day } else { // previous_time is later than current time! // Must assume that previous time refers to // a previous day... }