ctime

Status
Not open for further replies.

sum1nowhere

Baseband Member
Messages
85
I am trying to compare the time in my C++ program to various other constants. I am using system("time /t"); How can I assign the time to an integer variable so it can a be compared to other things such as: if (variable > 12:00) or something like that.
 
Look at some of the functions in <ctime>. Because "time /t" returns a string you'll have to parse it and generate a struct tm and use mktime() to convert it to time_t. If your using "time /t" to get the current time, don't because time() will give you the current time as time_t. difftime() will allow you to compare two times and return the difference in seconds.
 
As I understand it you are comparing a string time to the system time.

You need to two time values of type time_t to used by the function difftime(). The current time of the system can be got from the function "time_t time(time_t *);". The second time value can be gotten from somewhere else, it is best to put the values into a struct tm. A struct tm holds the different elements of time such as seconds, minutes, hours etc. By using the function "time_t mktime(struct tm *time)" you can convert the second time into time_t which can be compared. Its best to get the second time first, i.e. the one which isn't the current time.

Code:
//Parse the external time (e.g. one from a file or somewhere else) and populate the structure.
struct tm first_tm;
second_tm.secs = 0;
second_tm.minutes = 1;
second_tm.days = 5;
//etc.

//Convert it to time_t.
time_t first_time = mktime(&first_tm);
//Get the current time.
time_t current_time = time(NULL);
//Returns the different in seconds 
//E.g. 
//	current_time - first_time OR
//	later time - earlier time
double time_different = difftime(current_time, first_time);
A good place to look is here ctime (time.h) - C++ Reference
 
All I want is for a program to give the correct greeting such as good afternoon or something. So I am comparing the current time to a constant such as 12:00. I don't know how to go about getting the check variable into the right format to be compared to the current time. So is it possible to have like if(currtime > noon) so it compares the current time to the constant noon.
 
Status
Not open for further replies.
Back
Top Bottom