#include <iostream>
#include <ctime>
using namespace std;
int main()
{
double seconds;
struct tm birth = {0}; //10-28-1955
birth.tm_year = 55;
birth.tm_mon = 9;
birth.tm_mday = 28;
birth.tm_sec = 0;
struct tm present = {0}; //2-10-2021
present.tm_year = 121;
present.tm_mon = 1;
present.tm_mday = 10;
present.tm_sec = 0;
time_t p1 = mktime(&present);
time_t b1 = mktime(&birth);
seconds = (difftime(p1, b1));
seconds /= 86400;
cout << "Bill "
<< "Gates- " << seconds << "days" << endl;
}
Output :
Bill Gates- 18668.2days
I'm trying to use <ctime>
to try to find the number of days Bill Gates has been alive up to 2-10-2021. I get an answer of 18668.2; that is way off, as it should actually be around 20000 days.
While debugging, everything runs fine until line 21.
When it reaches line 22, b1
becomes -1.
I'm not sure how to fix this. The date I'm putting in for struct birth
seems fine.
When it reaches line 22, b1 becomes -1.
Sorry, but your C standard library is not enough to handle your dates. Use (or write) a different library that will allow to represent time before year 1970.
While at it, you are using C++ - no need to use C functions. Try using chrono library that is part of C++ standard library.