将字符串转换为日期C++ 我使用在C++中转换字符串和日期。

将字符串转换为日期C++ 我使用在C++中转换字符串和日期。,c++,datetime,date,C++,Datetime,Date,int main() { string dateFormat = "%m-%d-%Y %H:%M:%S"; tm startDate, endDate; if (strptime("1-1-2004 01:01:01", &dateFormat[0], &startDate) == NULL) { exit(1); } if (strptime("1-1-2010 00:00:00", &dateFormat[0], &endDat

int main() {
    string dateFormat = "%m-%d-%Y %H:%M:%S";
    tm startDate, endDate;
    if (strptime("1-1-2004 01:01:01", &dateFormat[0], &startDate) == NULL) { exit(1); }
    if (strptime("1-1-2010 00:00:00", &dateFormat[0], &endDate) == NULL) { exit(1); }
    cout << "startDate: " << asctime(&startDate)
         << " endDate: " << asctime(&endDate) << endl;

    time_t startDate2 = mktime(&startDate);
    time_t endDate2 = mktime(&endDate);

    cout << "startDate: " << asctime(localtime(&startDate2))
         << " endDate: " << asctime(localtime(&endDate2)) << endl;
    return 0;
}

为什么开始日期与结束日期相同?如果有人有更好的方法,请大声说出来

我明白了。asctime使用共享内存段将字符串写入。我必须把它复制到另一个字符串中,这样它就不会被覆盖

int main() {
    string dateFormat = "%m-%d-%Y %H:%M:%S";
    tm startDate, endDate;
    if (strptime("1-1-2004 01:01:01", &dateFormat[0], &startDate) == NULL) { exit(1); }
    if (strptime("1-1-2010 00:00:00", &dateFormat[0], &endDate) == NULL) { exit(1); }

    string sd1(asctime(&startDate));
    string ed1(asctime(&endDate));

    cout << "startDate: " << sd1
         << " endDate: " << ed1 << endl;

    time_t startDate2 = mktime(&startDate);
    time_t endDate2 = mktime(&endDate);

    string sd2(asctime(localtime(&startDate2)));
    string ed2(asctime(localtime(&endDate2)));

    cout << "startDate: " << sd2
         << " endDate: " << ed2 << endl;
    return 0;
}
int main() {
    string dateFormat = "%m-%d-%Y %H:%M:%S";
    tm startDate, endDate;
    if (strptime("1-1-2004 01:01:01", &dateFormat[0], &startDate) == NULL) { exit(1); }
    if (strptime("1-1-2010 00:00:00", &dateFormat[0], &endDate) == NULL) { exit(1); }

    string sd1(asctime(&startDate));
    string ed1(asctime(&endDate));

    cout << "startDate: " << sd1
         << " endDate: " << ed1 << endl;

    time_t startDate2 = mktime(&startDate);
    time_t endDate2 = mktime(&endDate);

    string sd2(asctime(localtime(&startDate2)));
    string ed2(asctime(localtime(&endDate2)));

    cout << "startDate: " << sd2
         << " endDate: " << ed2 << endl;
    return 0;
}