简体   繁体   English

如何比较日期?

[英]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之前,将tm结构的所有成员初始化为零。 strptime only fills those members for which there's a format specifier; strptime只填充那些有格式说明符的成员; 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. 当您的日期是“ YYYY-mm-dd”格式的字符串时,这是一种特殊情况,其中字符串的小于运算符给出的结果与假设日期类的小于运算符相同。 This is because the date is stored in "big endian" format, each number in the date is also "big endian". 这是因为日期以“ big endian”格式存储,日期中的每个数字也都是“ 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. 同上用于平等比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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