Tuesday, March 24, 2009

Get Current Time in C++

The ATL/MFC way:
/*Output Current Time is: 03/24/09 15:54:43*/



#include <atltime.h> // for CTime

#include <atlstr.h> // for CString

#include <iostream>



int main()

{

CString s(CTime::GetCurrentTime().Format("%c"));

std::wcout << L"Current Time is: "<< s.GetString();

}







The Boost Way:

/* Uses the clock to get the local time

*

* Expected Output something like:

* 2002-Mar-08 16:30:59

*/



#include "boost/date_time/posix_time/posix_time.hpp"

#include <iostream>



int main()

{

using namespace boost::posix_time;

using namespace boost::gregorian;



//get the current time from the clock -- one second resolution

ptime now = second_clock::local_time();



std::cout << L"Current Time is: "

<< to_simple_wstring(now)

<< std::endl;

return 0;

}

No comments:

Post a Comment