简体   繁体   中英

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

hi there i can compare people birthday in format YYYY-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.

我会在time_t值上使用difftime并与一周内的秒数进行比较...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM