本文介绍了将字符串转换为日期c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用< time.h>在c ++中的字符串和日期之间进行转换。

I'm using < time.h > to convert between strings and dates in 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

为什么开始日期与结束日期相同?如果任何人有更好的方式这样做,请说出来。

Why is the start date the same as the end date? Also if anyone has a better way of doing this please speak up.

推荐答案

我想出来了。 asctime使用共享内存段来写字符串。我必须将它复制到另一个字符串,以便它不会被覆盖。

I figured it out. asctime uses a shared piece of memory to write the strings to. I have to copy that to another string so that it does not get overwritten.

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

这篇关于将字符串转换为日期c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 20:08