time() function in C++

In this guide, you will learn what is time() function is in C++ programming and how to use it with an example.

1. time() Function Overview

The time() function in C++ is used to get the current calendar time. It returns the current time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). The function is declared in the <ctime> header file.

Signature:

time_t time(time_t* timer);

Parameters:

- timer: Pointer to a time_t object where the current calendar time will be stored. If this argument is a null pointer, the return value is not stored.

2. Source Code Example

#include <iostream>
#include <ctime>

int main() {
    time_t now;

    // Get the current calendar time
    time(&now);

    // Print the current time
    std::cout << "Current time: " << ctime(&now);

    return 0;
}

Output:

Current time: [Varies, e.g., "Sat Aug 26 23:21:15 2023\n"]

3. Explanation

1. A time_t variable named now is declared.

2. The time() function is called with the address of now to store the current time.

3. The ctime() function is used to convert the time_t value into a human-readable string format.

4. The result is printed to the console, displaying the current date and time.


Comments