将字符串转换为日期C++
问题描述:
我使用< time.h>在C++中的字符串和日期之间进行转换。将字符串转换为日期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
为什么开始日期一样的结束日期?此外,如果任何人有更好的方式做到这一点,请说出来。
答
我想通了。 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;
}