Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

date

compare

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.

like image 353
quartaela Avatar asked May 10 '11 13:05

quartaela


People also ask

How can I compare two dates in C?

Consider the problem of comparison of two valid dates d1 and d2. There are three possible outcomes of this comparison: d1 == d2 (dates are equal), d1 > d2 (date d1 is greater, i.e., occurs after d2) and d1 < d2(date d1 is smaller, i.e., occurs before d2).

How do I compare dates in different formats?

function compare() { var d1=new Date('2020-01-23'); //yyyy-mm-dd. var d2=new Date('2020-01-21'); //yyyy-mm-dd.

How do you compare two date functions?

To handle equality comparison, we use the date object alongside the getTime() date method which returns the number of milliseconds. But if we want to compare specific information like day, month, and so on, we can use other date methods like the getDate() , getHours() , getDay() , getMonth() and getYear() .


2 Answers

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

like image 195
R.. GitHub STOP HELPING ICE Avatar answered Oct 06 '22 08:10

R.. GitHub STOP HELPING ICE


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);
}
like image 23
Mel Avatar answered Oct 06 '22 08:10

Mel