Days Since a Given Date

Dave Sinkula 0 Tallied Votes 757 Views Share

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
*/
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.