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

First Method
Printing current date and time using time()

Second Method

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to print current date and time
// using time and ctime.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
  
int main()
{
    // declaring argument of time()
    time_t my_time = time(NULL);
  
    // ctime() used to give the present time
    printf("%s", ctime(&my_time));
    return 0;
}

chevron_right


Output:

It will show the current day, date and localtime, 
in the format Day Month Date hh:mm:ss Year

Third Method
Here we have used chrono library to print current date and time . The chrono library is a flexible collection of types that tracks time with varying degrees of precision .
The chrono library defines three main types as well as utility functions and common typedefs.
-> clocks
-> time points
-> durations

Code to print current date, day and time .

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to print current date and time
// using chronos.
#include <chrono>
#include <ctime>
#include <iostream>
  
using namespace std;
  
int main()
{
    // Here system_clock is wall clock time from
    // the system-wide realtime clock
    auto timenow =
      chrono::system_clock::to_time_t(chrono::system_clock::now());
  
    cout << ctime(&timenow) << endl;
}

chevron_right


Output:

It will show the current day, date and localtime, 
in the format Day Month Date hh:mm:ss Year


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : sanskar27jain



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.