Time & Date program

March 5, 2008 · By mahesh 

This article tells you how to show time & date on your C++ program.I’m using Dev-C++ IDE for this article,you can use any other if you want.But using Turbo & other IDE’s will require you to change your code as per their standard.As usual, I will explain all of the code at the end of the article.

If you’re using Dev-C++,then click File >New >Project >Console Application. Choose C++ as language.And save the project to some proper directory.This will open up the Main.cpp file which contains following code:
#include "cstdlib"
#include "iostream"

using namespace std;
int main(int argc, char *argv[])</br>
{
 system(”PAUSE”);
 return EXIT_SUCCESS;
}

Now you’ve to add few lines to your existing code in order to show the system time & date in your program.

#include <time.h>
Add the following line of code in main function.

char timebuf[32];
long timeval;
time(&timeval);
strftime(timebuf,32,"%a %d%b%Y %H:%M:%S",localtime(&timeval));
cout << "Today's day, date and time is : " << timebuf << endl;

That’s it.You don’t have to add any more lines to this code.Now your code looks like thefollowing code:
using namespace std;
int main(int argc, char *argv[])
{
 char timebuf[32];
long timeval;
time(&timeval); 
 
strftime(timebuf,32,”%a %d%b%Y %H:%M:%S”,localtime(&timeval));
cout << “Today’s day, date and time is : ” << timebuf << endl;
 
system(”PAUSE”);
return EXIT_SUCCESS;
}
After execution this program will show something like this:
Today's day, date and time is Wed 19March2008 12:43:00

Code explaination
In above program we’ve added the time.h header file.This file may be required by some
compilers.If you want to check if program works without it then go ahead.In next code snippet We’ve declared character array with length 32 characters.Also timeval varibale as long,which is pointing to the current local time.At the end,we’ve formatted the day,date and time to display.You can change the order or skip any if you want.Again there are many ways to format and display time & date.You can do some experiment and show as per your requirement.

There are a lot of different ways to modify this, and the limit is basically your imagination.You can use any IDE of your choice but this article used DevC++(Mingw) for this to work.If you’re Turbo C++ 3 user then you should check the manual with time.h file and it’s usage. If you have any questions feel free to comment.You can even ask your problems at onecore.ning.com

Comments

Leave a Reply