calculating birthday based on the number of days the user input

1.5k Views Asked by At

hello I'm trying to to calculate a person birthday by using the days the users inputs. I'm kind of new to the ctime library but what i came up with is the difference between two dates to get the number of days. From my knowledge i do have of ctime; i know ctime have a built in struct tm that consist of min,secs,hour,day,month and year. i tried using asctime to put them in individual but it made my logic more confusing. that i use difftime to find the difference between the dates. Like so :

struct tm a = { 0, 0, 0, 1, 1, 91 }; /* my birthday */
struct tm b = { 0, 0, 0, 3, 11, 114 }; /* today's date */
time_t x = mktime(&a);
time_t y = mktime(&b);
if (x != (time_t)(-1) && y != (time_t)(-1))
{
    double days = difftime(y, x) / (60 * 60 * 24);
    cout << ctime(&x);
    cout << ctime(&y);
    cout << "difference = " << days << " days" << endl;
}

The Output is: differnce = 8706 days

The problem is that users inputs 8706 days to get my birthday or their birthday. This code in reverse if it make sense. Can you help me figure out the logic in solving the problem.

2

There are 2 best solutions below

2
On BEST ANSWER

I didn't get what you really want but if your trying to let the user enter number of days and you will get his birthday it's easy,just write struct tm a = { 0, 0, 0, a, b, c}; /* my birthday */ and if number of days is 8706 int c=8706/365; // the greatest divisor it should give u 23 and you will get the remaining by int temp=23*365=8395; and then you will make int remaining =8706-8395=311; and u continue to find the months and days.. Hope this is your question.

2
On

If you can use Boost:

#include <iostream>
#include "boost/date_time/gregorian/gregorian.hpp"

using namespace std;
using namespace boost::gregorian;

int main(){
    days d;
    cin >> d;
    date today = day_clock::local_day();
    date birth = today - d;
    date bday(today.year(), birth.month(), birth.day());
    if(bday < today) bday = date(today.year()+1, birth.month(), birth.day());
    cout << bday;
}