C Time Functions - C difftime






Returns the difference in seconds between two times.

Prototype

double difftime (time_t end, time_t beginning);

Parameter

This function has the following parameter.

end
Higher bound of the time interval whose length is calculated.
beginning
Lower bound of the time interval whose length is calculated.

If this describes a time point later than end, the result is negative.

Return

The result of (end-beginning) in seconds as a floating-point value of type double.

Example


#include <stdio.h> /* printf */
#include <time.h> /* time_t, struct tm, difftime, time, mktime */
// w  w  w  . j  av a 2s . co  m
int main (){
  time_t now;
  struct tm newyear;
  double seconds;

  time(&now);  /* get current time; same as: now = time(NULL) */

  newyear = *localtime(&now);

  newyear.tm_hour = 0; newyear.tm_min = 0; newyear.tm_sec = 0;
  newyear.tm_mon = 0;  newyear.tm_mday = 1;

  seconds = difftime(now,mktime(&newyear));

  printf ("%.f seconds since new year in the current timezone.\n", seconds);

  return 0;
} 

       

The code above generates the following result.





Example 2


#include <stdio.h>
#include <time.h>
 /* ww  w.  j av a2  s.co  m*/
int main(void){
    time_t now;
    time(&now);
 
    struct tm beg;
    beg = *localtime(&now);
 
    // set beg to the beginning of the month
    beg.tm_hour = 0;
    beg.tm_min = 0;
    beg.tm_sec = 0;
    beg.tm_mday = 1;
 
    double seconds = difftime(now, mktime(&beg));
 
    printf("%.f seconds have passed since the beginning of the month.\n", seconds);
 
    return 0;
}

The code above generates the following result.