[英]C++ converting string to time_t question
Im trying to convert a string such as "12 August 2011" into time_t or that seconds elapsed, or whatever so I can use it to compare a list of dates. 我试图将诸如“2011年8月12日”之类的字符串转换为time_t或经过的秒数,或者其他什么,我可以用它来比较日期列表。
At the moment, I have tried the following but the output seems to equal false! 此刻,我尝试了以下但输出似乎等于假! Also, the seconds elapsed seem to keep changing?
而且,经过的秒数似乎在不断变化?
Is this correct? 这个对吗?
#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);
}
You should initialize the structs before use. 您应该在使用前初始化结构。 Try this:
尝试这个:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.