Time/Date Calculations

Dave Sinkula 0 Tallied Votes 131 Views Share

Some issues with date/time calculations.

[Perhaps I ought to edit this one day and better describe it.]

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

const char *dtstamp(int days, const char *format)
{
   static const char *errmsg[] = 
   {
      "the calendar time is not available",
      "the specified time cannot be converted to local time",
      "the calendar time cannot be represented",
      "strftime conversion failure"
   };
   static char result [ 80 ];
   time_t t;
   struct tm *local;
   /*
    * Try to obtain the implementation's best approximation to the current
    * calendar time.
    */
   if ( time ( &t ) == (time_t)(-1) )
   {
      return errmsg[0];
   }
   /*
    * Try to convert the calendar time pointed into a broken-down time.
    */
   local = localtime ( &t );
   if ( !local )
   {
      return errmsg[1];
   }
   /*
    * It might be prudent to check for integer over/underflow here, but I'll
    * live dangerously and just adjust by the offset.
    */
   local->tm_mday += days;
   /*
    * Try to convert the adjusted broken-down time into a calendar time value.
    */
   t = mktime ( local );
   if ( t == (time_t)(-1) )
   {
      return errmsg[2];
   }
   /*
    * Try to convert the adjusted calendar time pointed into a broken-down time.
    */
   local = localtime ( &t );
   if ( !local )
   {
      return errmsg[1];
   }
   /*
    * Try to created a formatted output string.
    */
   if ( !strftime ( result, sizeof result, format, local ) )
   {
      return errmsg[3];
   }
   return result;
}

int main(void)
{
   static const char Iso8601[] = "%Y-%m-%dT%X";
   int offset;
   offset = -10;
   printf("%d days from today is %s\n", offset, dtstamp(offset, Iso8601));
   offset = 10;
   printf("%d days from today is %s\n", offset, dtstamp(offset, Iso8601));
   return 0;
}

/* my output
-10 days from today is 2005-05-06T22:31:11
10 days from today is 2005-05-26T22:31:11
*/