How to Generate Time and Date in C++

This Program will generate the current date and time in C++ Program. The ctime library is used to get the time and date.
 

Source Code

#include <conio.h>   //kbhit()
#include <time.h>    //time_t localtime() asctime()
#include <unistd.h>  //sleep
#include <iostream>  //cout
#include <windows.h>
using namespace std; //cout

int main()
{
            //1 means letting the loop true for all time
    while(1)
    {
     cout<<"Press Any key to Stop \n";
     time_t t=time(0);
 //     For Date only
     struct tm * now = localtime( & t );
 cout << (now->tm_year + 1900) << '-' 
 << (now->tm_mon + 1) << '-'
 <<  now->tm_mday
 << endl;
//     For Time and Date only
 cout << "\nTime and Date :" << asctime(localtime(&t)) <<endl;
 Sleep(1);
     if(kbhit())
        {
        cout<<"Key Pressed \n";
        //TO Exit loop on any key Press
        break;
        }
        system("CLS");
    }
}

Output of the Program

Time and Date in C++

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.

1 comments: