Boost boost :: posix_time :: time_duration for string

Hi, I am using the Posix Time system. I have a class

class event{
private:
boost::posix_time::ptime time;

//some other stuufff

public:
string gettime(void);
}

//functions
string event::gettime(void){
return  to_iso_extended_string(time.time_of_day());
}

but to_iso_extended_string does not accept type

boost::posix_time::time_duration

type only

boost::posix_time

it can be seen here

I want to return a string for later output etc

How can I solve this problem? I do not see a method in boost to convert

boost::posix_time::time_duration

to a string. I am new to both C ++ and apologizing if it is really simple.

+3
source share
4 answers

use operator <

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

#include <iostream>

int
main()
{
    using namespace boost::posix_time;
    const ptime start = microsec_clock::local_time();
    const ptime stop = microsec_clock::local_time();
    const time_duration elapsed = stop - start;
    std::cout << elapsed << std::endl;
}
mac:stackoverflow samm$ g++ posix_time.cc -I /opt/local/include    
mac:stackoverflow samm$ ./a.out
00:00:00.000485
mac:stackoverflow samm$ 

Note that you need to use a header posix_time.hpp, not posix_time_types.hppto enable I / O statements.

+5
source

You tried just using the <<Operator:

std::stringstream ssDuration;
ssDuration << duration;

std::string str = ssDuration.str();
+1

I think formatting a string using time_duration is annoying. I wanted to format the length of time indicated in seconds to d HH: mm: ss (for example, 1 10:17:36 in 123456 seconds). Since I could not find a suitable formatting function, I did some manual work:

const int HOURS_PER_DAY = 24;

std::string formattedDuration(const int seconds)
{
    boost::posix_time::time_duration a_duration = boost::posix_time::seconds(seconds);

    int a_days = a_duration.hours() / HOURS_PER_DAY;
    int a_hours = a_duration.hours() - (a_days * HOURS_PER_DAY);

    return str(boost::format("%d %d:%d:%d") % a_days % a_hours %  a_duration.minutes() % a_duration.seconds());
}

Not very elegant, but the best I came up with.

+1
source

You can use increment date / time to convert time to string.

-1
source

Source: https://habr.com/ru/post/1786422/


All Articles