Printing time

From Yefu's notes
Jump to: navigation, search

If you want to print time with the resolution of a second, std c++ is good enough:

        void WriteLine(const std::string& line)
            auto now = std::chrono::system_clock::now();
            auto in_time_t = std::chrono::system_clock::to_time_t(now);
            std::tm time;
            localtime_s(&time, &in_time_t);
            std::cout<<std::put_time(&time, "%Y-%m-%d %X")<<": "<<line<<std::endl;

If you need milisecond-level resolution, try boost:

std::wstring FormatTime(boost::posix_time::ptime now)
  using namespace boost::posix_time;
  static std::locale loc(std::wcout.getloc(),
                         new wtime_facet(L"%Y%m%d_%H%M%S"));

  std::basic_stringstream<wchar_t> wss;
  wss << now;
  return wss.str();

Note do not use it in managed c++.