View Single Post
Old Jun 6th, 2006, 12:07 PM   #4
jim mcnamara
Hobbyist Programmer
 
Join Date: Jun 2005
Location: New Mexico
Posts: 228
Rep Power: 4 jim mcnamara is on a distinguished road
Consider using strptime - which is pretty flexible. Most compilers now support it. Older Windows compilers don't. Most calendric work uses strptime to convert dates to seconds in the epoch, which is the basis for time and date calculations in C.

#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
/* 86400 seconds per day */
#define DAY 86400      

/* 
   lose the
   th, nd, st suffixes if they exist 
*/
char *remove_th_nd_st(const char *src)
{
	const char *values[3]={{"th "}, {"nd "},{"st "} };
	char *dest=strdup(src);
	char *p=NULL;
	int i=0;
	
	while(i<3)
	{
		if( (p=strstr(src,values[i++]))==NULL ) continue;
		if( !isdigit(*(p-1)) ) continue;
		p+=3;
		sprintf(dest,"%d %s",atoi(src),p); 
		break;
	}
	return dest;
}
 
/* return time difference in days 
   date1 = recent date
   date1 = older date
   ---otherwise you get a negative value which may be okay.
*/   
int date_diff(const char *date1, const char *date2)
{
    int retval=0;
    const char *fmt="%d %b %Y";
    struct tm now, then;
    char *wdate1=remove_th_nd_st(date1);
    char *wdate2=remove_th_nd_st(date2);       
    
    if ( strptime(wdate1,fmt,&now)==NULL ||
        strptime(wdate2,fmt,&then)==NULL )
    {
    	perror("Bad date format");
    	exit(EXIT_FAILURE);
    }
    now.tm_isdst = -1;  /* force mktime to get daylight savings */
    then.tm_isdst = -1;
    retval=difftime(mktime(&now),mktime(&then));
    retval=retval/DAY;
    free(wdate1);
    free(wdate2);
    return retval;
}

int main()
{
    char now[32]={0x0};
    char then[32]={0x0};
	strcpy(then,"14th June 1983");
    strcpy(now,"15th April 2006");
    printf("Date difference in days: %s - %s = %d\n",
         now,then,date_diff(now,then) );
    strcpy(now,"1st June 2005");     
    printf("Date difference in days: %s - %s = %d\n",
         now,then,date_diff(now,then) );
    strcpy(now,"2nd August 2014");
    printf("Date difference in days: %s - %s = %d\n",
         now,then,date_diff(now,then) );
    strcpy(now,"1st July 1975");
    printf("Date difference in days: %s - %s = %d\n",
         now,then,date_diff(now,then) );             
    return 0;     
}
jim mcnamara is offline   Reply With Quote