The time()
function in C++ returns the current calendar time as an object of type time_t
. It is defined in the ctime header file.
Example
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// use time() with NULL argument
cout << time(NULL);
return 0;
}
// Output: 1629799688
time() Syntax
The syntax of the time()
function is:
time(time_t* arg);
time() Parameters
The time()
function takes the following parameters:
- arg: pointer to a
time_t
object which (if notNULL
) stores the time.
time() Return Value
The time()
function returns:
- On Success - the current calendar time as a value of type
time_t
. - On Failure -
-1
which is casted to typetime_t
.
time() Prototype
The prototype of time()
as defined in the ctime header file is:
time_t time(time_t* arg);
Example 1: C++ time()
#include <iostream>
#include <ctime>
using namespace std;
int main() {
time_t current_time;
current_time = time(NULL);
cout << current_time;
cout << " seconds has passed since 00:00:00 GMT, Jan 1, 1970";
return 0;
}
Output
1629810340 seconds has passed since 00:00:00 GMT, Jan 1, 1970
Example 2: C++ time() with Reference Pointer
#include <iostream>
#include <ctime>
using namespace std;
int main() {
time_t current_time;
// stores time in current_time
time(¤t_time);
cout << current_time;
cout << " seconds has passed since 00:00:00 GMT, Jan 1, 1970";
return 0;
}
Output
1629810340 seconds has passed since 00:00:00 GMT, Jan 1, 1970