Good day Gentl'men!

Is there a way in c++ to convert a string variable that holds time of format like "17:30" to time_t variable?
Lets say!:

#include<iostream>
#include<ctime>
using namespace std;
int main()
{
time_t timein,timeout;
float timediff;
string stimein,stimeout;
cout<<"Enter time-in: ";
cin>>stimein;

cout<<"Enter time-out: ";
cin>>stimeout;
//convertion from string to time_t here
timediff=difftime(timeout,timein);
cou<<timediff<<endl;
return 0;
}

Thank you!

Of course.

Parse the string into it's components (a 17 and a 30).
Fill a time structure (defined in time.h) with the appropriate values.
Call the appropriate time function in to convert the structure into time_t.

I call mktime(). One crevet -- you need to initialize all fields of struct tm to 0 before using it becuse mktime() will return an error of any of the fields contain random junk values. Here's an easy/quick way to do that.

struct tm tm;
memset(&tm,0,sizeof(struct tm));
commented: A crucible or melting pot? Or did you mean caveat? ;o) +14

Thank you WaltP, Ancient Dragon!
Here is my revised code that parsed the time input. One last thing, how to assign the struct tm from the parsed value then put it back to time_t?

#include<string>
#include<iostream>
#include<sstream>
#include<ctime>
using namespace std;
int main()
{
struct tm vartime;
string timinput,hr_time,min_time;
stringstream parsedtime;

memset(&vartime,0,sizeof(struct tm));

cout<<"Enter time-in: ";
cin>>timinput;
parsedtime<<timinput;

getline(parsedtime, hr_time, ':' );
getline(parsedtime, min_time, ':' );

//assignment to struct tm here

system("pause");
return 0;
}

Thank you for helping!

Do you know how to work with structures yet?
If so, it's no different from what you already know.
If not, you might want to wait until you get to the chapter on structures before tackling this program.

Thank you WaltP!

I believe assigning a value to a struct variable is something like this:

vartime.tm_hour=hr_time;
vartime.tm_min=min_time;

But I get error that says ."Invalid conversion from string to int in assignment."
Any suggestion to this problem?

Finally a no error code but why is the output is not correct. Example if you enter "17:30" the result is -1. Any suggestion to solve the problem? My code so far:

#include<iostream>
#include<sstream>
#include<ctime>
using namespace std;

int main()
{
struct tm vartime;
time_t finaltimein;
string timinput,hr_time,min_time;
int timein_hr, timein_min;
stringstream parsedtime;

memset(&vartime,0,sizeof(struct tm));

cout<<"Enter time-in: ";
cin>>timinput;
parsedtime<<timinput;

getline(parsedtime, hr_time, ':' );
getline(parsedtime, min_time, ':' );

timein_hr=atoi(hr_time.c_str());
timein_min=atoi(min_time.c_str());

vartime.tm_hour=timein_hr;
vartime.tm_min=timein_min;
finaltimein=mktime(&vartime);
cout<<finaltimein<<endl;

system("pause");
return 0;
}

Thank you for helping!

you also need to set a year/month/day because time_t is the number of seconds since 1 Jan 1970 to the specified date.

time_t is the number of seconds since 1 Jan 1970 to the specified date.

While it is indeed the canonical epoch, there's no guarantee that time_t represent the number of seconds since 1/1/1970. For example, I very seriously considered using 1/1/1900 as the epoch for my time.h library, to the point where it was functional, before changing my mind and conforming to convention.

Anyway, a good technique for setting up the tm structure when you only care about the time portion is to initialize it to the current day:

time_t t = time(0);       // Get the current datetime as time_t
tm *info = localtime(&t); // Break it down into a local calendar object

// Update desired fields
info->tm_hour = new_hour;
info->tm_min = new_min;

// mktime normalizes the calendar object
if (mktime(info) != (time_t)-1) {
    // info is now safe to use
}

Thank you Ancient Dragon, deceptikon!

Ive modified the code but when I enter a time value ex. "17:30" it outputs "1346027413". Can we make it "17:30" now in a time_t datatype so that I can use difftime function? Here is my code so far:

#include<iostream>
#include<sstream>
#include<ctime>
using namespace std;
int main()
{
time_t timenow,finaltimein,finaltimeout;
string timinput,hr_time,min_time;
int timein_hr, timein_min;
double timediff;
stringstream parsedtime;

timenow=time(0);
tm *info = localtime(&timenow);

cout<<"Enter time-in: ";
cin>>timinput;
parsedtime<<timinput;

getline(parsedtime, hr_time, ':' );
getline(parsedtime, min_time, ':' );

timein_hr=atoi(hr_time.c_str());
timein_min=atoi(min_time.c_str());

info->tm_hour=timein_hr;
info->tm_min=timein_min;

finaltimein=mktime(info);
parsedtime.clear();
cout<<finaltimein<<endl;

system("pause");
return 0;
}

Thank you!

Can we make it "17:30" now

If you want the time_t converted back to a string then call strftime() to create the string, which works a little bit like printf()

Maybe this is unclear. First is I have the time in a string datatype, I want to use difftime to get the time difference, so the time in a string datatype must be put in a time_t datatype for the difftime to work. This is what the program should be. The only problem for me now is how to store the time in a struct info to time_t base on the code above?

Thank you!

Did you display the values in your tm structures to verify the data is correct? If it isn't, there's no sense comverting anything.

Also, please format your code so it can be read and understood easier. When you get into more complex programs this will be a major help to you. Also, stop using system("pause"). Here's why

Thank you WaltP!
cin.get(); is not working for me to pause the console window. Everthing on struct tm is correct as ive cout the value from that ive passed.. The only thing I wanted is to store the value from struct tm to time_t.

What was you expecting time_t to contain? If struct tm is correct then the value for time_t is also probably correct. Recall from our previous discussion in this thread that time() returns time_t that is the number of seconds since some pre-determined date, quite often 1 Jan 1970, but that date can be anything the compiler wants it to be.

If that's not what you are wanting, then you could calculate it yourself by setting it to the number of seconds since midnight of the current day. Just convert HH and MM to seconds. The problem with that approach is that it makes it pretty difficult to find the difference between two times because the two times may or may not be on different dates.

Thank you Ancient Dragon!
tm has now this value.tm_hour=17, tm_min=30. I want this value to be stored in time_t datatype to use difftime. So if I have "08:30" as timein, and "17:30" as timeout the result of difftime() must be 9.5. timediff=difftime(timeout,timein)..

cin.get(); is not working for me to pause the console window.

Then your basic input concepts are leaving the input buffer dirty. Change your cin>>timinput to a getline().

So if I have "08:30" as timein, and "17:30" as timeout the result of difftime() must be 9.5. timediff=difftime(timeout,timein)..

How do you get 9.5? That looks wrong to me.

thank you WaltP!

So if I have "08:30" as timein, and "17:30" as timeout the result of difftime() must be 9.5. timediff=difftime(timeout,timein)..

The result actually is 9.sorry for that.

tm has now this value.tm_hour=17, tm_min=30. I want this value to be stored in time_t datatype to use difftime.

Then use mktime() to generate a time_t out of a tm structure. As long as the structure is valid, mktime() will give you a valid time_t conversion, otherwise it'll return (time_t)-1.

The time library is actually very simple as far as usage (the internal implementation can get hairy though). time() gives you the current time. gmtime() and localtime() convert a time_t into a tm structure. mktime() converts a tm structure into a time_t, and also normalizes out of range values for most of the fields.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.