C++ Time function

WHAT IS TIME( ) IN C++?

  • In C++, the time( ) function will return the current calendar time as an object of type time_t.
  • The C++ standard library does not provide a proper data type for date and time it inherits the structs and functions for date and time manipulation from C.
  • To access the date and time related functions you need to include <ctime> header file. The four types of time are time_t, clock_t, size_t and tm.

THE PROTOTYPE OF TIME( ) IS:

      time_t time(time_t* arg)

 

The time( ) function points a pointer to time_t object as its argument and returns the current calendar time as a value of type time_t.

LET US HAVE A LOOK AT THE EXAMPLE TO UNDERSTAND THIS FUNCTION:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
 
#include <ctime>
 
using namespace std;
 
int main() {
 
   // current date/time based on current system
 
   time_t current = time(0);
 
   // convert now to string form
 
   char* dt = ctime(&current);
 
   cout << “The local date and time is: “ << dt << endl;
 
   // convert now to tm struct for UTC
 
   tm *gmtm = gmtime(&current);
 
   dt = asctime(gmtm);
 
   cout << “The UTC date and time is:”<< dt << endl;
 
}

Output : 

The local date and time is: Sun Mar 29 07:43:00 2020

The UTC date and time is:Sun Mar 29 07:43:00 2020