The following sample program converts a given string in an argument string to a number of days. Output Example:
% ./nd 2011-06-18 1971-02-10 invalid 2010invalid
38 days
-14699 days
2147483647 days
2147483647 days
: , -1 , INX_MAX.
#include <sys/param.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#define ONE_DAY (24 * 3600)
int main(int argc, char *argv[])
{
int i;
if( argc < 2 )
return (64);
for( i=1; i < argc; i++ )
{
time_t res;
res = num_days(argv[i]);
printf("%d days\n", res);
}
return(0);
}
int num_days(const char *date)
{
time_t now = time(NULL);
struct tm tmp;
double res;
memset(&tmp, 0, sizeof(struct tm));
if( strptime(date, "%F", &tmp) == NULL )
return INT_MAX;
res = difftime(mktime(&tmp), now);
return (int)(res / ONE_DAY);
}