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.
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);
//c开发者_开发问答har 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;
}
精彩评论