将字符串转换为日期c ++

时间:2011-02-06 03:56:19

标签: c++ datetime date

我正在使用< time.h>在c ++中转换字符串和日期。

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;
}

我得到这个作为输出:

startDate: Thu Jan  1 01:01:01 2004
 endDate: Thu Jan  1 01:01:01 2004

startDate: Thu Jan  1 01:01:01 2004
 endDate: Thu Jan  1 01:01:01 2004

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

1 个答案:

答案 0 :(得分: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;
}
相关问题