Copyright © Programs ++
Design by Dzignine
Saturday 28 April 2012

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.


2 comments:

  1. 1. time_t sec; Does this means we are declaring a variable sec of type time_t

    2.could you please explain time(&sec), we are passing the memory location of the variable that we created, when i printed, this gave a long int value 1340875232

    3. in your program you are calcultaion time between 1st jan 1970 and the day u run ur program, is 1st jan 1970 the default time ?

    ReplyDelete
  2. 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.

    ReplyDelete

Comment Here....