我试图将诸如“2011年8月12日”之类的字符串转换为time_t或秒数,或者其他任何内容,我可以用它来比较日期列表。
目前,我已尝试以下但输出似乎等于假!此外,经过的秒数似乎在不断变化?
这是对的吗?
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <time.h>
#include <stdio.h>
using namespace std;
int main()
{
struct tm tmlol, tmloltwo;
time_t t, u;
t = mktime(&tmlol);
u = mktime(&tmloltwo);
//char test[] = "01/01/2008";string test = "01/01/2008";
strptime("10 February 2010", "%d %b %Y", &tmlol);
strptime("10 February 2010", "%d %b %Y", &tmloltwo);
t = mktime(&tmlol);
u = mktime(&tmloltwo);
cout << t << endl;
cout << u << endl;
if (u>t)
{
cout << "true" << endl;
}
else if (u==t)
{
cout << "same" << endl;
}
else
{
cout << "false" << endl;
}
cout << (u-t);
}
答案 0 :(得分:8)
您应该在使用前初始化结构。试试这个:
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <time.h>
#include <stdio.h>
using namespace std;
int main()
{
struct tm tmlol, tmloltwo;
time_t t, u;
// initialize declared structs
memset(&tmlol, 0, sizeof(struct tm));
memset(&tmloltwo, 0, sizeof(struct tm));
strptime("10 February 2010", "%d %b %Y", &tmlol);
strptime("10 February 2010", "%d %b %Y", &tmloltwo);
t = mktime(&tmlol);
u = mktime(&tmloltwo);
cout << t << endl;
cout << u << endl;
if (u>t)
{
cout << "true" << endl;
}
else if (u==t)
{
cout << "same" << endl;
}
else
{
cout << "false" << endl;
}
cout << (u-t) << endl;
return 0;
}