1

I read whole info about boost::chrono and still didn`t get how to convert boost::chrono::system_clock to string in easy way. For example, I want to get current time and convert it to string in next format: hh:mm:ss. For example I wan receive smth like this - 24:55:03. I can receive current time in next way:

auto current_time = boost::chrono::system_clock::now()

How simply to format current_time to string. It sad but I can`t find any help in boost documentation and in google.

AeroSun
  • 2,401
  • 2
  • 23
  • 46

2 Answers2

0

So boost::chrono should be fully supported in C++11's std::chrono.

Which I believe is now fully supported by Visual Studio 2013 and gcc 4.8?

Anyway you can print using: put_time

There are a tremendous number of format specifiers in the link, you can use those to customize the output to your needs.

It's important to note that put_time is just a stream manipulator. If you need to get your time in a string you'll need to use put_time with a stringstream.

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • Thx! Ok, it works. But, unfortunately, I must to do too much actions for this simple task. I expect smth like one function (or max two functions). I expect that boost/std chrono will be more simple that posix_time operation. And I sad that it is not. – AeroSun Dec 05 '14 at 21:28
  • @AeroSun You can use the [Anonymous `stringstream` trick](http://stackoverflow.com/q/19665458/2642059) to do this all in one line if that solves your problem: `const std::string foo = static_cast(std::ostringstream() << std::put_time(/*your code here*/)).str()` – Jonathan Mee Dec 05 '14 at 21:34
  • Hmmm, there are present streams, ok I will test is it more faster that I format time in usual way. Thanks a lot! Once more - do you know how add the millisecond to format? Like this - hh:hh:ss:llll – AeroSun Dec 05 '14 at 22:24
  • @AeroSun this is the wrong thing to use if you are trying to count milliseconds. That's not in [struct tm](http://www.cplusplus.com/reference/ctime/tm/) – Jonathan Mee Dec 06 '14 at 00:31
0

In this example, I will use std::localtime and std::put_time from the standard library to print a date obtained with boost.chrono to std::cout.
You can change the format as desired.

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

int main() {
    auto now{boost::chrono::system_clock::to_time_t(boost::chrono::system_clock::now())};
    std::tm* ptm{std::localtime(&now)};
    std::cout << std::put_time(ptm, "%Y/%m/%d %H:%M:%S") << std::endl;
    return 0;
}

compiler commands:

g++ x1.cpp -lboost_chrono

sample output:

2023/05/24 14:30:05