Skip to content

3.8 printing a date

avalyaev edited this page May 15, 2013 · 1 revision

##Problem Given a number of seconds since the epoch date, print a date and time in human readable format.

##Solution Use Boost DateTime library.

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

int main ( ) 
{

  std::cout << second_clock::universal_time() << std::endl;   //PRINT locale date-time  in a form 2013-May-15 07:09:22
  std::cout << second_clock::local_time() << std::endl;       //print universal date - time  in a form 2013-May-15 03:10:32

  return 0;
}

You can customise output format using boost time_facet.

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

int main ( ) 
{
  time_facet *facet = new time_facet("%d-%b-%Y %H:%M:%S");
  std::cout.imbue(std::locale(std::cout.getloc(), facet));
  std::cout << second_clock::universal_time() << std::endl; //15-May-2013 07:21:35
  std::cout << second_clock::local_time() << std::endl;     // 15-May-2013 03:22:25

  return 0;
}
Clone this wiki locally