Print system time in C++ (3 different ways)


There are different ways by which system day, date and time can be printed in Human Readable Form.

First way

Using time() − It is used to find the current calendar time and have arithmetic data type that store time
localtime() − It is used to fill the structure with date and time
asctime() − It converts Local time into Human Readable Format

Day Month Date hour:month:second Year

Example

#include<iostream>
#include<ctime> // used to work with date and time
using namespace std;
int main() {
   time_t t; // t passed as argument in function time()
   struct tm * tt; // decalring variable for localtime()
   time (&t); //passing argument to time()
   tt = localtime(&t);
   cout << "Current Day, Date and Time is = "<< asctime(tt);
   return 0;
}

Output

if we run the above program then it will generate the following output

Current Day, Date and Time is = Tue Jul 23 19:05:50 2019

Second way

Chrono library is used to measure elapsed time in seconds, milliseconds, microseconds and nanoseconds

Example

#include <chrono>
#include <ctime>
#include <iostream>
Using namespace std;
int main() {
   auto givemetime = chrono::system_clock::to_time_t(chrono::system_clock::now());
   cout << ctime(&givemetime) << endl;
}

Output

if we run the above program then it will generate the following output

Current Day, Date and Time is = Tue Jul 23 19:05:50 2019

Third way

Example

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
   time_t givemetime = time(NULL);
   printf("%s", ctime(&givemetime)); //ctime() returns given time
   return 0;
}

Output

if we run the above program then it will generate the following output

Tue Jul 23 20:14:42 2019
raja
Published on 30-Jul-2019 12:01:14
Advertisements