-
Displaying Time
HEY, i need to display the current time and date in my program and use variable to store each of the time values like
a = 10
b = 29
c = 31
printf(``%d : %d : %d``, a,b,c);
which then give the output as -
10:29:31
any ideas how to save the time in variables in C....
i am using C in windows 7 and my complier is Bloodshed Dev C++
-
This functionality is supplied in the time.h header file. A good documentation page for it is here:
<time.h>
For an example, to get the current hours, minutes and seconds you could do it like this
Code:
time_t now = time(NULL);
struct tm *tmptr = localtime(&now);
printf("hours: %d, minutes: %d, seconds: %d\n",
tmptr->tm_hour, tmptr->tm_min, tmptr->tm_sec);
-
Lets say at the end of the program, i want to make a projection for the user that
if current time is 20:39:07 then the job will be done by 23:49:37
how do i add to each of the hours, minutes and seconds
-
The type time_t is simply an integer value representing a number of seconds. Therefore, if your program is expected to take one hour, you need only to add 3600 to the time_t variable which represents the current time. This effectively shifts the current time to the future (or the past). The function localtime will convert this time_t value into fields of tm_hour, tm_min and tm_sec
-
Can u explain to me what the struct, tm, tmptr
the tmptr-> and how this code works
-
struct tm is how the various parts of the time are defined. Look at the documentation I linked to; its all explained there in detail.
-> means to access a field in the case that the container is a pointer to a struct
If you are new to pointers to struct, then one approach is to just use the code and study the details of the symbols later. You should work your own examples with structs, fields, etc. in order to understand the details behind them.
-
Another thing, what if i want to measure the amount of time taken by the user to finish the code, how would i do that?
That time = 0 at the beginning and once the program finishes it displays that "you took 67 seconds to finish the game"
-
The line
time_t t0 = time(NULL);
will get the current time as a number of seconds. If you later call time(NULL) and assign it to t1, then the amount of time elapsed is t1-t0.