Tuesday 8 September 2009

Getting Date and Time in C++ on Windows

The program example below shows three aproaches to get the date and time. MSDN references are embedded in the program.


#include<iostream>
#include<time.h> //For approach1 and approach3
#include <Windows.h> //For approach 2

using namespace
std;

void
approach1(void)
{

char
dateStr [9];
char
timeStr [9];
//http://msdn.microsoft.com/en-us/library/585kfedd(VS.80).aspx
_strdate_s( dateStr);
//http://msdn.microsoft.com/en-us/library/yb2bth04(VS.80).aspx
_strtime_s( timeStr );
cout<<"\nApproach 1"<<endl;
cout<<"Current date is: "<<dateStr<<endl;
cout<<"Current time is: "<<timeStr<<endl;
}


void
approach2(void)
{

SYSTEMTIME systemTime;
//http://msdn.microsoft.com/en-us/library/ms724390(VS.85).aspx
GetSystemTime(&systemTime);
cout<<"\nApproach 2"<<endl;
cout<<"Current date is: "<<systemTime.wMonth<<"/"<<systemTime.wDay<<"/"<<systemTime.wYear<<endl;
cout<<"Current time is: "<<systemTime.wHour<<":"<<systemTime.wMinute<<":"<<systemTime.wSecond<<endl;
}


void
approach3(void)
{

//http://www.daniweb.com/forums/thread64803.html
char buffer[BUFSIZ] = { '\0' } ;
time_t now = time( &now ) ;
struct
tm local_time;
//http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx
localtime_s( &local_time, &now ) ;
cout<<"\nApproach 3"<<endl;
//http://msdn.microsoft.com/en-us/library/fe06s4ak(VS.71).aspx
strftime( buffer, BUFSIZ, "%m/%d/%Y", &local_time ) ;
cout<<"Current date is: "<< buffer << endl ;
strftime( buffer, BUFSIZ, "%H:%M:%S", &local_time ) ;
cout<<"Current time is: "<< buffer << endl ;
}


int
main()
{

approach1();
approach2();
approach3();
return
0;
}






The output is as follows:

No comments:

Post a Comment