Calculating time difference in C (days, hours, minutes, seconds) -


i've tried calculate time difference between days / hours / minutes / seconds result not good. tried lower them , turn them in seconds, brought them same format(d/h/m/s). target calculate time spent, between 2 times. like: 1day, 2hours, 3minutes , 54 seconds , 3days, 3hours, 10 minutes , 23 seconds. here i`ve tried:

#include <stdio.h> #include <stdlib.h>  int main() {      int day1, hour1, min1, sec1, day2, hour2, min2, sec2, totaltime;     printf("enter input:");      scanf("%d%d%d%d%d%d%d%d", &day1, &hour1, &min1, &sec1, &day2, &hour2, &min2, &sec2);      totaltime = (day2-day1)*86400 + (hour2-hour1)*3600 + (min2-min1)*60 + (sec2-sec1);       printf("d: %d\n", totaltime / 86400);      totaltime = totaltime % 86400;       printf("h: %d\n", totaltime / 3600);      totaltime = totaltime & 3600;       printf("m: %d\n", totaltime / 60);      totaltime = totaltime % 60;       printf("s: %d\n", totaltime);      return 0; } 

but don`t work expected.

given poor way calculate time difference, there 2 problems:

  1. scanf cannot separate integers
  2. hour difference wrong

try this:

#include <stdio.h> #include <stdlib.h>  int main() {     int day1, hour1, min1, sec1, day2, hour2, min2, sec2, totaltime;     printf("enter input:");     scanf("%d,%d,%d,%d,%d,%d,%d,%d", &day1, &hour1, &min1, &sec1, &day2, &hour2, &min2, &sec2);     totaltime = (day2 - day1) * 86400 + (hour2 - hour1) * 3600 + (min2 - min1) * 60 + (sec2 - sec1);      printf("d: %d\n", totaltime / 86400);     totaltime = totaltime % 86400;      printf("h: %d\n", totaltime / 3600);     totaltime = totaltime % 3600;      printf("m: %d\n", totaltime / 60);     totaltime = totaltime % 60;      printf("s: %d\n", totaltime);      return 0; } 

a better way calculate time difference using difftime function


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -