Monday, July 27, 2009

How to find difference between two different dates using builtin date structure in C?

Using C language builtin structures how to find the number of days between two different dates.


Note:


Two dates want to be read from the user.


Not using the system date.

How to find difference between two different dates using builtin date structure in C?
This will work in C but i decided to use c++ but you will just have to change the cout to printf, etc...





#include %26lt;iostream%26gt;


#include %26lt;ctime%26gt;





int main()


{


struct std::tm a = {0,0,0,24,6,105}; /* June 24, 2005 */


struct std::tm b = {0,0,0,21,1,107}; /* Jan 21, 2007 */


std::time_t x = std::mktime(%26amp;a);


std::time_t y = std::mktime(%26amp;b);


if ( x != (std::time_t)(-1) %26amp;%26amp; y != (std::time_t)(-1) )


{


double difference = std::difftime(y, x) / (60 * 60 * 24);


std::cout %26lt;%26lt; std::ctime(%26amp;x);


std::cout %26lt;%26lt; std::ctime(%26amp;y);


std::cout %26lt;%26lt; "difference = " %26lt;%26lt; difference %26lt;%26lt; " days" %26lt;%26lt; std::endl;


}


return 0;


}





Simply put, you just have to have the user input the date but then you break them down into components that can be placed into the structure and away you go.


No comments:

Post a Comment