C++ time() function with example

In this tutorial, we will learn about the C++ time() function with example.

In C++, the standard library does not provide any particular data type for date and time. It generally inherits from C. For this, we have to include the header file <ctime> which includes all date-time related functions and structures. The data type for the time in C++ is time_t.

The time() function has the following functionality:

  • It returns the current calendar time of the system.
  • This calendar time is in the form of seconds after date 01, January 1970.
  • It returns this time as an object of the type time_t.
  • If the system does not have any time, then -1 is returned by this function.
  • It takes one argument which is a pointer to the time_t. This pointer can be null or reference variable of the type time_t.

Syntax:

time_t time(time_t *timeargument);

Program to illustrate the use of C++ time() function with example:

#include<ctime>
#include<iostream>
using namespace std;
int main()
{
    time_t currentsystemtime;
    time_t currentsystime;
    currentsystemtime=time(&currentsystemtime);
    currentsystime=time(NULL);
    cout << currentsystemtime << " seconds have passed since 01-01-1970."<<endl;
    cout << currentsystime << " seconds have passed since 01-01-1970."<<endl;
    return 0;
}

Output:

1581355526 seconds have passed since 01-01-1970.
1581355526 seconds have passed since 01-01-1970.

This program takes two time_t type variables. Then one of the variables is assigned the time variable with its reference and the other with the time variable with NULL as its argument. In both cases, the time() returns the current system time in seconds is after the date 01, January 1970. These variables contain the same output as shown above.

I hope this post was helpful to illustrate the use of the C++ time() function. Thanks for reading!

Recommended Posts:
Get IP address from hostname in C++ for Windows
Find the most frequent word in a string in C++

Leave a Reply

Your email address will not be published. Required fields are marked *