1
#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.

code with output

While debugging, everything runs fine until line 21.

on line 21

When it reaches line 22, b1 becomes -1.

on line 22

I'm not sure how to fix this. The date I'm putting in for struct birth seems fine.

Ron
  • 13
  • 3
  • 1
    Please edit your code and output into the question as text. – Retired Ninja Feb 27 '21 at 04:13
  • 2
    [`mktime`](https://en.cppreference.com/w/c/chrono/mktime) behavior for dates before the epoch (1970) is implementation defined, see [mktime returns -1 when given a valid struct tm](https://stackoverflow.com/questions/14127013/mktime-returns-1-when-given-a-valid-struct-tm) for example. – dxiv Feb 27 '21 at 04:39
  • 2000 days is less than 10 years. How old is Windows, again? – Davis Herring Feb 27 '21 at 18:31

1 Answers1

0

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.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111