Velocity Reviews > Get the difference between two dates in terms of days

# Get the difference between two dates in terms of days

gops
Guest
Posts: n/a

 02-10-2004
Hi,

Can anyone send me a specific example of getting the differncce
between two dates in terms of no of days using a C library function.

I have tried using difftime, but I am not successfull so far. Pls can
any one help me out.

Regards
Gopal

Richard Heathfield
Guest
Posts: n/a

 02-10-2004
gops wrote:

> Hi,
>
> Can anyone send me a specific example of getting the differncce
> between two dates in terms of no of days using a C library function.
>
> I have tried using difftime, but I am not successfull so far. Pls can
> any one help me out.

This is just a quick hack. I have actually checked that it basically works,
but it's not hugely elegant code:

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

void stotm(struct tm *p, const char *s)
{
int i;
struct tm blank = {0};
*p = blank;

for(i = 0; i < 4; i++)
{
p->tm_year *= 10;
p->tm_year += *s++ - '0';
}
p->tm_year -= 1900;
for(i = 0; i < 2; i++)
{
p->tm_mon *= 10;
p->tm_mon += *s++ - '0';
}
--p->tm_mon;
p->tm_mday = 10 * (*s++ - '0');
p->tm_mday += *s++ - '0';
}

void calcdiff(const char *old, const char *new)
{
struct tm t1 = {0};
struct tm t2 = {0};
time_t tt1 = {0};
time_t tt2 = {0};

stotm(&t1, old);
stotm(&t2, new);
tt1 = mktime(&t1);
tt2 = mktime(&t2);
if(tt1 != -1 && tt2 != -1)
{
long day = 0;
double d = difftime(tt1, tt2);
if(d < 0) d *= -1.0;
day = d / 86400;
printf("%ld day%s\n", day, day == 1 ? "" : "s");
}
else
{
fprintf(stderr, "bad date format: %ld %ld\n", (long)tt1, (long)tt2);
}
}

int main(int argc, char **argv)
{
if(argc < 3 || strlen(argv[1]) < 8 || strlen(argv[2]) <
{
fprintf(stderr, "Learn.\n");
}
else
{
if(strcmp(argv[1], argv[2]) < 0)
{
calcdiff(argv[1], argv[2]);
}
else
{
calcdiff(argv[2], argv[1]);
}
}
return 0;
}

--
Richard Heathfield : http://www.velocityreviews.com/forums/(E-Mail Removed)
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton