Start New Discussion within our Software Development Community

This snippet shows one way to calculate the number of days since a given date until present time. Note that this code will not work for dates outside of the current epoch, which typically begins on January 1, 1970.

#include <stdio.h>
#include <time.h>

int days_diff(int y, int m, int d)
{
   time_t now, then;
   struct tm date = {0};

   date.tm_year = y - 1900;
   date.tm_mon  = m - 1;
   date.tm_mday = d;

   if ( time ( &now ) != (time_t)(-1) )
   {
      then = mktime ( &date );
      if ( then != (time_t)(-1) )
      {
         fputs(ctime(&now),  stdout);
         fputs(ctime(&then), stdout);
         return difftime(now, then) / (24 * 60 * 60);
      }
   }
   return 0;
}

int main(void)
{
   printf("days = %d\n", days_diff(1970, 3, 8));
   return 0;
}

/* my output
Mon Aug 22 11:51:06 2005
Sun Mar 08 00:00:00 1970
days = 12951
*/
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.