Ariyan
Ariyan

Reputation: 15158

difftime returns incorrect value in MinGW

I'm trying to calculate difference between two time_t.
but difftime returns its first parameter instead of the difference!
My code is:

 #include <windows.h>
 #include <stdio.h>
 #include <time.h>
 #include <unistd.h>

 int main(){
     time_t etime_t,now_t;
     double time_diff;
     now_t=1388525484L;
     etime_t=1389338644L;
     time_diff=difftime(now_t,etime_t);
     printf("%f",time_diff);
 }

And it prints:

1388525484.000000

I'm compiling with GCC (in MinWG)
What is the problem?

Upvotes: 4

Views: 2143

Answers (2)

Marian
Marian

Reputation: 7472

A MinGw bug. They compile difftime to a call of a standard windows function. However, they call a 32 bit version of difftime, even if arguments are 64 bits. This gives the expected result as it substracts higher half of the first argument (which is 0) from its lower half. See bug report here. It can be temporarily fixed by inserting

#define _USE_32BIT_TIME_T 1

before including time.h

Upvotes: 6

user3177100
user3177100

Reputation:

/*my little lab:*/
#include <sys/types.h>
#include <stdio.h
#include <time.h>
#include <unistd.h>
int main(void)
{
 time_t etime_t, now_t;
 struct tm timev_n; 
 struct tm timev_e; 
 struct tm *ptimev_n = &timev_n; 
 struct tm *ptimev_e = &timev_e; 

 double time_diff;
 now_t= 1388525484L;
 etime_t=   1389338644L;
 ptimev_n= gmtime_r(&now_t, ptimev_n );
 ptimev_e= gmtime_r(&etime_t, ptimev_e );
 printf (" now:  %s \n", asctime(ptimev_n)); 
 printf (" end:  %s \n", asctime(ptimev_e)); 
 // time_diff=difftime(now_t,etime_t);
 time_diff=difftime(etime_t, now_t);
 printf("%f \n",time_diff);
 etime_t = (time_t)  time_diff;
 ptimev_e= gmtime_r(&etime_t, ptimev_e );
 printf ("back to the 70's diff:  %s \n", asctime(ptimev_e)); 

 return 1;
 }

gives output:

" now: Tue Dec 31 21:31:24 2013

end: Fri Jan 10 07:24:04 2014

813160.000000 back to the 70's diff: Sat Jan 10 09:52:40 1970 " pls check the order of parameters to difftime, maybe your system has unsigned time_t ?

Upvotes: 1

Related Questions