开发者

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

hi there i can compare people birthday in format 开发者_StackOverflowYYYY-MM-DD with string (strcmp) functions. but i need compare todays date with person's birthday to display if his/her birthday is in 7 days or not_?. i searched "time.h" library but couldn't managed it. i appreciated if you can help.


I would use difftime on the time_t values and compare against the number of seconds in a week...


The following sample program converts a given string on the argument line to the number of days. Example output:

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

Edit: Decided that -1 is not a nice failure indicator so using INX_MAX instead.

#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);
}


You want the strptime function for converting the string to a struct tm. It is part of Posix, but not the C standard. http://www.cs.potsdam.edu/cgi-bin/man/man2html?3+strptime has an example for how to use strptime.

You then want to add 7 to the tm_mday field, convert the result to a time_t (with mktime), and then compare that to the current time (from time(NULL)), so see if the input date is within the next week.

It is not portable, according to the C standard, to do arithmetic on time_t values, which is why you should modify the struct tm fields instead. Likewise, you need to do the comparison with current time using difftime.


Populate a struct tm with the birthdate and convert that to a time_t.

Get the current time_t using time().

One week is 86400*7 seconds.

Check the difference between the birthdate time_t and the current time_t.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜