简体   繁体   中英

How do i compare dates?

I have date in string type then I need to compare these 2 dates

I've tried this but it shows me strange output

string str="2019-1-12";
    string str1="2019-1-13";
    tm timeDate;
    tm timeDate1;
    strptime(str.c_str(),"%Y-%m-%d ", &timeDate); 
    time_t time_input = mktime(&timeDate);
    strptime(str1.c_str(),"%Y-%m-%d ", &timeDate1); 
    time_t time_input1 = mktime(&timeDate1);

    double timeDiff = difftime(time_input,time_input1);
    cout<<timeDiff;

Make it

tm timeDate = {};
tm timeDate1 = {};

In other words, initialize all members of tm structures to zero before strptime call. strptime only fills those members for which there's a format specifier; the rest remains garbage.

With this change, your code works

less than,equal to,greather than another date

When your dates are strings in the format of "YYYY-mm-dd", this is a special case where the less-than operator for string gives the same result as the less-than operator would for a hypothetical date class. This is because the date is stored in "big endian" format, each number in the date is also "big endian".

The string less-than operator compares each character one-by-one and if one is less than the other, then that is the result of the entire comparison.

The only thing you need to do is to make sure that your month and day fields are each two characters (put a zero in front if they are one character), and then compare the strings.

cout << (str < str1) << '\n';

Ditto for equality comparison.

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