Comparing dates in C with (using time.h library)

Hi, I can compare YYYY-MM-DD people's birthday with string (strcmp) functions. but I need to compare today's date with a person’s birthday to show if his birthday is 7 days or not_ ?. I searched for the library "time.h" but could not manage it. I appreciated if you can help.

+5
source share
4 answers

I would use difftimefor values time_tand compare the number of seconds per week ...

+5
source

The following sample program converts a given string in an argument string to a number of days. Output Example:

% ./nd 2011-06-18 1971-02-10 invalid 2010invalid
38 days
-14699 days
2147483647 days
2147483647 days

: , -1 , INX_MAX.

#include <sys/param.h>
#include <time.h>
#include <string.h>
#include <stdio.h>

#define ONE_DAY (24 * 3600)

int main(int argc, char *argv[])
{
        int i;

        if( argc < 2 )
                return (64); // EX_USAGE

        for( i=1; i < argc; i++ )
        {
                time_t res;

                res = num_days(argv[i]);
                printf("%d days\n", res);
        }

        return(0);
}

int num_days(const char *date)
{
        time_t now = time(NULL);
        struct tm tmp;
        double res;

        memset(&tmp, 0, sizeof(struct tm));
        if( strptime(date, "%F", &tmp) == NULL )
                return INT_MAX;

        res = difftime(mktime(&tmp), now);
        return (int)(res / ONE_DAY);
}
+3

strptime struct tm. Posix, C. http://www.cs.potsdam.edu/cgi-bin/man/man2html?3+strptime strptime.

7 tm_mday, time_t ( mktime), ( time(NULL)), , - .

C , time_t, struct tm. , , difftime.

+2

tm time_t.

Get the current time_t using time ().

One week - 86400 * 7 seconds.

Check the difference between the date of birth and the current time_t.

+1
source

All Articles