2

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

1 Answer 1

8

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Simpler: struct tm tmlol = { 0 }; struct tm tmloltwo = { 0 };. (gcc may warn about missing initializers; feel free to ignore it.)
@ildjarn: Interesting. That's illegal in C; I didn't know C++ allowed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.