Denster is right; There is a million and one ways to do this. When dealing with time in "C", I'd rather convert everything in seconds from the EPOCH and then do my date arithmetic. This stub program gets the number of whole days, but could easily be changed to get days, hours, minutes, etc. I also assume the user entered hours, minutes, and seconds are zero.
Expanding on Denster's idea, I change the user entered month, day, year strings to integer; build a time structure for the user entered data, and convert that to seconds. The purests out there are going to say I should have used the difftime function to get the difference between two time_t types.
Maybe, but time_t is a long, and we know sooner or later it has to change. Most everybody knows that timet overflows Tue Jan 19 03:14:07 2038 GMT
I learned everything I know on this subject from P.J. Plaugher's book, The Standard "C" Library.
Regards,
Ed
Schaefer
/*
* Get the number of seconds between system date and user entered date
*/
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
void main()
{
time_t systime, caltime; /* time_t is a long */
struct tm *systm, usertm;
char *mmc="4"; /* user entered date */
char *ddc="5";
char *yyc="2002";
long secondsin24=86400; /* seconds in day */
int mm, dd, yy;
long timediff;
time(&systime); /* get the system time in seconds since EPOCH */
systm=localtime(&systime); /* and return a pointer to the time structure */
printf("time in seconds since EPOCH is %ld\n", systime);
mm=atoi(mmc); /* convert to int */
dd=atoi(ddc);
yy=atoi(yyc);
/* build the user time structure */
usertm.tm_year = yy - 1900;
usertm.tm_mon = mm - 1;
usertm.tm_mday = dd;
usertm.tm_hour = 0;
usertm.tm_min = 0;
usertm.tm_sec = 0;
usertm.tm_isdst = systm->tm_isdst;
/* get time in seconds from the time structure */
caltime = mktime(&usertm);
printf("time in seconds for caltime is %ld\n", caltime);
/* don't care if time difference is negative */
timediff=caltime-systime;
if(timediff < 0)
timediff = timediff * (-1);
printf("Number of days since user entered date: %ld\n", timediff/secondsin24);
The problem though has been solved, what happen when u have to find the difference between the two dates say
date1 == may 01, 2002
date2 == october 10, 2001
some calculation has to be done for the year. the logic mentioned by me helps in calculation of the year, and when its leap year, the same can be added as (y2 - y1) % 4
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.