The time() function is defined in <ctime> header file.
time() prototype
time_t time(time_t* arg);
The time() function takes a pointer to time_t
object as its argument and returns the current calendar time as a value of type time_t
.
If arg is not a null pointer, the returned value is also stored in the object pointed to by arg.
time() Parameters
- arg: pointer to a time_t object which (if not null) stores the time.
time() Return value
- On success, the time() function returns the current calendar time as a value of type
time_t
. - On failure it returns -1 which is casted to type
time_t
.
Example 1: How time() function works with return value?
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
time_t current_time;
current_time = time(NULL);
cout << current_time << " seconds has passed since 00:00:00 GMT, Jan 1, 1970";
return 0;
}
When you run the program, the output will be:
1489924627 seconds has passed since 00:00:00 GMT, Jan 1, 1970
Example 2: How time() function works with reference pointer?
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
time_t current_time;
// Stores time in current_time
time(¤t_time);
cout << current_time << " seconds has passed since 00:00:00 GMT, Jan 1, 1970";
return 0;
}
When you run the program, the output will be:
1489924627 seconds has passed since 00:00:00 GMT, Jan 1, 1970