C++ Standard Library C++ STL Library

C++ <ctime> - time() Function



The C++ <ctime> time() function returns the current calendar time as a value of type time_t and if the argument is not a null pointer, it also sets this value to the object pointed by timer.

The function returns an integral value representing the number of seconds generally holding the number of seconds elapsed since 00:00, Jan 1 1970 UTC (i.e., a unix timestamp). Although libraries may use a different representation of time.

Syntax

time_t time (time_t* timer);

Parameters

timer Specify pointer to a time_t object to store the time, or a null pointer.

Return Value

On success, returns current calendar time as a value of type time_t. On failure, returns a value of -1. If the argument is not a null pointer, the return value is the same value as stored in the location pointed to by timer.

Example:

The example below shows the usage of time() function.

#include <iostream>
#include <ctime>
using namespace std;
 
int main (){
  time_t t = time(NULL);
    
  cout<<"Time elapsed since the epoch began: "
      <<t<<" seconds\n";

  //displaying the date & time
  cout<<asctime(localtime(&t));

  return 0;
}

The possible output of the above code could be:

Time elapsed since the epoch began: 1618580793 seconds
Fri Apr 16 13:46:33 2021

❮ C++ <ctime> Library