Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

C++ program to display current date and time

This program is about printing the date and time using C++. The C library contains the time.h header that deals with time and dates. Before heading further, i would like to mention a new type of variable of the type time. It is the time_t type, which is a variable of time and is used to store time related information when dealing with time functions included in the time.h header file.

It is declared as follows :

time_t seconds; // this declares a variable of the type time_t

Please note that it is not a fundamental data type;

Now, to print the date and time, we need to store it first. This task is done with the time() function, that calculates the time and stores it in a variable of type time_t. The value that is calculated is a long numeric value. To print the date and time in a more readable and user friendly format, the ctime() function is used which converts the date and time into a string for display purposes.

The program below demonstrates the use of time() and ctime() functions to display time and date. It also displays the time elapsed from 1st January 1970 till now. For more information, please e-mail me or leave a comment.

// Program to print current date and time using C++

#include <iostream>
#include <ctime>

int main()
{
     time_t sec;
     // creates and instance of the time variable time_t
     time(&sec);
     std::cout<<" Current Date and time : "<<ctime(&sec);
     std::cout<<"\n Time elapsed from 1st January 1970 --> "<<sec<<" seconds ";
     std::cout<<"\n Time elapsed from 1st January 1970 --> "<<sec/3600<<" hours ";
     std::cout<<"\n Time elapsed from 1st January 1970 --> "<<(sec/3600)/24<<" days ";
     std::cout<<"\n Time elapsed from 1st January 1970 --> "<<((sec/3600)/24)/7<<" weeks ";
     std::cout<<"\n Time elapsed form 1st Jaunary 1970 --> "<<((sec/3600)/24)/365<<" years ";
     std::cout<<"\n Time elapsed from 1st January 1970 --> "<<(float)(((sec/3600)/24)/365)/10<<" decades \n";
     return 0;
} // end of main
------ OUTPUT ------









Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.




This post first appeared on Programs ++, please read the originial post: here

Share the post

C++ program to display current date and time

×

Subscribe to Programs ++

Get updates delivered right to your inbox!

Thank you for your subscription

×