Here is some code of mine that prints out the relative date according to the current time:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (int argc, char *argv[])
{
int i = 1;
struct tm date = {0};
char relativeDays[80];
char* temp = strtok(argv[1], "/");
while(temp != 0)
{
switch(i++)
{
case 1:
date.tm_mon = atoi(temp) - 1;
break;
case 2:
date.tm_mday = atoi(temp);
break;
case 3:
date.tm_year = atoi(temp) - 1900;
}
temp=strtok(NULL, "/");
}
i = (int) difftime(time(NULL), mktime(&date))/86400;
sprintf(relativeDays, "%d", abs(i));
if (i > 0) printf("%s\n", strcat(relativeDays, " days ago."));
else if (i < 0) printf("%s\n", strcat(relativeDays, " days from now."));
else printf("Today\n");
return 0;
}
Sample input and output:
$ ./date 12/8/2013 2 days ago. $ ./date 12/10/2013 Today $ ./date 12/24/2013 13 days from now.
Any thoughts on how to improve the code, specifically how to make it shorter?