Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) GetTime

 

GetTime is a time code snippet to obtain now's time.

 

GetTime can depend on two different libraries:

 

 

 

 

 

Boost Boost version of GetTime

 

 

Operating system: Ubuntu Ubuntu 10.04 LTS Lucid Lynx

IDE: Qt Creator Qt Creator 2.0.0

Project type: Console Console application

Compiler: G++ 4.4.1

Libraries used:

 

 

 

 

 

#include <iostream>
#include <sstream>
#include <string>
#include <boost/date_time/posix_time/posix_time.hpp>

//From http://www.richelbilderbeek.nl/CppGetTime.htm
const std::string GetTime()
{
  //Get the local time
  boost::posix_time::ptime now
    = boost::posix_time::second_clock::local_time();
  //Convert the time to std::stringstream
  std::stringstream s;
  s << now.time_of_day();
  //Return the std::string
  return s.str();
}

int main()
{
  const std::string s = GetTime();
  std::cout << s << '\n';
}

 

Screen output:

 

12:50:44

 

 

 

 

 

STL STL version of GetTime

 

Operating system: Ubuntu Ubuntu 10.04 LTS Lucid Lynx

IDE: Qt Creator Qt Creator 2.0.0

Project type: Console Console application

Compiler: G++ 4.4.1

Libraries used:

 

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <sstream>
#include <string>

///TimeToStr converts std::time_t to std::string.
///From http://www.richelbilderbeek.nl/CppTimeToStr.htm
const std::string TimeToStr(const std::time_t& time)
{
  return std::ctime( &time);
}

//From http://www.richelbilderbeek.nl/CppGetTime.htm
std::time_t GetTimeT()
{
  return std::time(0);
}

//From http://www.richelbilderbeek.nl/CppGetTime.htm
const std::string GetTime()
{
  return TimeToStr(GetTimeT());
}

int main()
{
  const std::time_t t = GetTimeT();
  std::cout << "Program started at " << GetTime() << '\n';
  std::system("./Pause 5");
  const std::time_t u = GetTimeT();
  std::cout << "Program ended at " << GetTime() << '\n';
  const int n_secs = std::difftime(u,t);
  std::cout << "Number of seconds passed: " << n_secs << '\n';
}

 

Screen output:

 

Program started at Fri Oct  1 20:48:47 2010
Program ended at Fri Oct  1 20:48:52 2010
Number of seconds passed: 5

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict