Convert char to time

Hi, I am trying to convert char to time and I found the following code. But it gives me a -1 on "converted" instead of time. What am I doing wrong? Please help.

#include <stdio.h>
#include <time.h>
#include <iostream>
using namespace std;


int main()
{
int hh, mm, ss;
char charTime[] = "20:44:57";
char *pTime = charTime;

struct tm when = {0};

sscanf_s(pTime, "%d:%d:%d", &hh, &mm, &ss);

when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);
cout << converted <<endl;

return 0;
}
What about the date? You want to assume the date is 1/1/1970?

You haven't shown the declaration and initialisation of when.
Hi kwb, I tried to put in the date as well but still has same result. The when is declared below with ( struct tm when = {0}; )

#include <stdio.h>
#include <time.h>
#include <iostream>
using namespace std;


int main()
{
int hh, mm, ss, dd, mth, yy;
char charTime[] = "1:1:1970:20:44:57";
char *pTime = charTime;

struct tm when = {0};

sscanf_s(pTime, "%d:%d:%d:%d:%d:%d", &dd, &mth, & yy, &hh, &mm, &ss);

when.tm_mday = dd;
when.tm_mon = mth;
when.tm_year = yy;
when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);
cout << converted <<endl;

return 0;
}
Please help. Thanks.
1
2
3
4
5
6
7
8
9
10
11
struct tm when ;
memset( &when, 0, sizeof(tm) ) ; // *****

// ...

when.tm_mday = dd;
when.tm_mon = mth - 1 ; // ***** Jan == 0, Dec == 11
when.tm_year = yy - 1900 ; // ***** years since 1900
when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;
Hi JLBorges,

Thanks for the code. I am trying to convert the struct tm to time_t format using mktime (converted = mktime(&when);) but it returns me a -1 which I read is an error.

I am also trying to compare time. For the moment, what I did was convert all the time to seconds and compare.
Thanks a lot JLBorges.
Topic archived. No new replies allowed.