Get the difference between two dates in terms of days

G

gops

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
 
R

Richard Heathfield

gops said:
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]) < 8)
{
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;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,037
Latest member
MozzGuardBugs

Latest Threads

Top