date difference problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ilyaw77
    New Member
    • Oct 2009
    • 8

    #1

    date difference problem

    Hi guys, I have a problem to calculate difference in date using difftime.
    Two strings are passed to the function day1="05/01/2007" and day2="04/30/2007" the difference I got is 2 days which is wrong since there is no 31st day in april. The most surprising part I can pass 04/31/2007 ang get the right difference without any error while creating struct tm. What am I doing wrong?
    Here is my programm:

    Code:
    int DaysDifference(string const& day1, string const& day2){
    	int day,month,year;
    	double diff;
    
    	day=StrToInt(day1.substr(3,2));
    	month=StrToInt(day1.substr(0,2));
    	year=StrToInt(day1.substr(6,4))-1900;
    	struct tm a= {0,0,12,day,month,year};
    
    	day=StrToInt(day2.substr(3,2));
    	month=StrToInt(day2.substr(0,2));
    	year=StrToInt(day2.substr(6,4))-1900;
    	struct tm b= {0,0,12,day,month,year};
    
    	time_t x = mktime(&a);
    	time_t y = mktime(&b);
    	if ( x != (time_t)(-1) && y != (time_t)(-1) ){
    		/*difftime returns difference in seconds*/
    		diff = difftime(x,y)/(60*60*24);
    	}
    	
    	return diff;
    }
    Thank you for the help
  • ilyaw77
    New Member
    • Oct 2009
    • 8

    #2
    Hey guys, I think I found my error, it should be:

    Code:
    month=StrToInt(day1.substr(0,2))-1;
    thnaks a lot though !!! :)

    Comment

    Working...