Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) GetTimestamp

 

GetTimestamp is a time code snippet to obtain the current time and date as a 'stamp', for example '2011_07_01_11_35_38' (at the 1st of July 2011, 11:35:38 AM).

 

 

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


///Copy_if was dropped from the standard library by accident.
//From http://www.richelbilderbeek.nl/CppCopy_if.htm
template<typename In, typename Out, typename Pred>
Out Copy_if(In first, In last, Out res, Pred Pr)
{
  while (first != last)
  {
    if (Pr(*first))
      *res++ = *first;
    ++first;
  }
  return res;
}

///Returns date in YYYY-MM-DD format
//From http://www.richelbilderbeek.nl/CppGetDateIso8601.htm
const std::string GetDateIso8601()
{
  const boost::gregorian::date today
    = boost::gregorian::day_clock::local_day();
  const std::string s
    = boost::gregorian::to_iso_extended_string(today);
  assert(s.size()==10);
  assert(s[4]=='-');
  assert(s[7]=='-');
  return s;
}

///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();
}

///Returns the current date and time as a YYYY_MM_DD_HH_MM_SS std::string,
///for example '2011_07_01_11_35_38'
///From http://www.richelbilderbeek.nl/CppGetTimestamp.htm
const std::string GetTimestamp()
{
  std::string s = GetDateIso8601() + '_' + GetTime();
  std::replace(s.begin(),s.end(),':','_');
  std::replace(s.begin(),s.end(),'-','_');
  return s;
}

int main()
{
  //Example output:
  //2011_07_01_11_37_27
  std::cout << GetTimestamp() << '\n';
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict