Swannie Swannie - 20 days ago 4x
C Question

Get days between a date and now using the time() function

I want to get a number of days from a certain date to current date.
Here is my current code that gets the days from 1/1/1970.

int days_since_my_birth(int day, int month, int year) {

time_t sec;
sec = time(NULL);

printf("Number of days since birth is %ld \n", sec / 86400);

return d;

Can I use the
function to get the number of seconds from a date I entered?


here is how i done it in the end. it doesnt work if the birthday entered is before 1970. thanks for all the help.

i only just started learning c so there is probably more efficient ways to do it.

int days_since_my_birth(int day, int month, int year) {

    //create a time struct and initailize it with the function parameters   
    struct tm time_info = { 0 };
    time_info.tm_year = year - 1900;
    time_info.tm_mon = month -1;
    time_info.tm_mday = day;

    //get the number of seconds from 1970
    int n = time(NULL);

    // convert the birthdate to seconds
    double birthday = mktime(&time_info);
    // convert the birthdate to days
    birthday = (birthday / 86400);
    //get the no of days alive by subtracting birthdate days
    int result = (n / 86400) - birthday;

    return result;