1

When i do compare 2 string current date and past date it shows me that current date is not bigger than past date.

I tried to compare str and str2 and the comparison is true.

string str="21/05/2019";
    string str2="7/06/2019";
    string c=GetCurrentDate();
    if(c>str)
    {
        cout<<"true";
    }

and function

inline string GetCurrentDate()
{
    auto t = time(nullptr);
    auto tm = *localtime(&t);
    ostringstream oss;
    oss << put_time(&tm, "%d/%m/%Y");
    auto strCurrentDate= oss.str();
    return strCurrentDate;
}

2 Answers2

3

You're better of using built in types to represent time.

But to answer your question, since you're comparing strings, it's probably using lexicographical comparison, which is not what you want.

"7/06/2019" < "8/09/2019" // even though the month is higher

because 7 just has a lower ascii value than 8, it returns true.

What you could do, although I am not recommending it, is format your date in "yyyy/mm/dd". This would work, but you'll have to make sure that you always add zeros when needed ("2019/06/31" and not "2019/6/31").

"yyyy/mm/dd" would work, because even though it will still be using lexicographical ordering, because the weight of the lexicographical value(ascii value) of any digit is tied to the actual value('actual date value')

"2019/mm/dd" > "2018/mm/dd";
"2019/06/dd" > "2019/05/dd" ;
"2019/06/25" > "2019/06/19";

But yeah, definitely use a built in type that's made for time/date if you can instead of strings.

0

Comparing strings is different from comparing date/time types. It is better to use some built-in type for representing dates, such as std::time::chrono or something alike. C++ gives you the tools to manipulate these type, so you don't need to reinvent the wheel.

Although I believe std::time is not "user-friendly", I suggest to have a look at the reference below.

https://en.cppreference.com/w/cpp/chrono/system_clock/now