比较来自字符串、char*或int的两个日期

Compare 2 dates from strings,char* or int

本文关键字:日期 两个 int 字符串 char 比较      更新时间:2023-10-16

我在这里有一个问题,我一直在尝试比较SYSTEMTIME的日期格式和文本文件(string)的日期。但这行不通。我试图将两者更改为字符串(使用osstringstream), char*和int(使用sscanf)进行比较,但没有运气。这很简单,我想做的就是获取当前系统日期,并将其与文本文件中的日期进行比较。下面是我的代码:

char szcurrentDate[MAX_PATH] = "";
char szdate_time[MAX_PATH];
SYSTEMTIME st;
GetLocalTime(&st);
GetDateFormat(LOCALE_USER_DEFAULT, NULL, &st, "yyyy-M-d ", szcurrentDate,
              MAX_PATH);  // current system date
// std::ostringstream mm;
// stringstream mm;
// mm << szcurrentDate;
MessageBoxA(NULL, szcurrentDate, "Attention", IDOK == IDCANCEL);
ifstream ifs(szFile);
string line;
while (!ifs.eof())
{
    getline(ifs, line);
    if ((line.find("TESTING_GET_DATE:") != string::npos))
    {
        std::string str = line.substr(
            17, 9);  // substract TESTING_GET_DATE: 2014-3-16 to  2014-3-16
        strcpy(szdate_time, str.c_str());
        if (szcurrentDate == szdate_time)
        {
            MessageBoxA(NULL, "Same", "Attention", MB_OK);
        }
        else
        {
            MessageBoxA(NULL, "blablabla", "Attention", MB_OK);
        }

注意:我试着只显示szcurrentDateszdate_time,他们显示的日期完全相同。stringchar*int格式

This:

strcpy(szdate_time, str.c_str());
if (szcurrentDate == szdate_time)

没有意义。您正在将c++字符串复制到C字符串(不必要),然后比较指针到两个char数组(它们永远不会相等,因为不比较内容,只比较地址)。

你可以这样修改:

if (szcurrentDate == str)

将对std::string调用operator==,它将比较字符串的内容。而且代码更少

不能使用==比较字符数组。这适用于字符串对象,但不适用于C风格的字符串。您需要对它们使用strcmp(),或者您需要对日期使用字符串对象。