C++ Program to print current Day, Date and Time


Current day, date and time are all calendar dates that are printed on screen. In c++, the ctime library contains all the methods and variables related to date and time.

You can also check current date and time details using the ctime library which contains methods to display time. The following methods are used to display details of date and time −

time() − The time() method is used to find the current time. The return time of the time() method is time_t. time_t is the data type that can store time.

localtime() − To convert the time_t type variables to a variable that can hold both date and time. The localtime() function converts time_t to a structure that can hold both date and time. It accepts the time() function as argument.

The data returned by localtime() method cannot be directly printed to the output screen. So, the asctime() method will return the date in the following form −

day month date hh:mm:ss year

Now, let’s put all these methods together into a program. This program uses methods of ctime and defines a time_t this variable is used to hold the current date and time using the time() method. The data from this variable is passed to the localtime() method whose returned data is passed to the asctime() method which returns user representable form and displays it.

Example

 Live Demo

#include<iostream>
#include<ctime>
using namespace std;
int main(){
   time_t timetoday;
   time (&timetoday);
   cout << "Calendar date and time as per todays is : "<< asctime(localtime(&timetoday));
   return 0;
}

Output

Calendar date and time as per today is : Mon Sep 9 18:56:33 2019

Updated on: 19-Sep-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements