Hello I am using boost 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 开发者_Python百科does not take type
boost::posix_time::time_duration
only type
boost::posix_time
this can be seen here
I want to return a string for later output e.t.c.
How can I solve this problem? I can't see a method in boost to convert
boost::posix_time::time_duration
to string. I am new to both C++ and boost so apologies if this is a real simple one.
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 you'll need to use the posix_time.hpp
header rather than posix_time_types.hpp
to include the I/O operators.
Have you tried simply using the << operator:
std::stringstream ssDuration;
ssDuration << duration;
std::string str = ssDuration.str();
I think the string formatting with time_duration is kind of annoying. I wanted to format a time duration specified in seconds into d HH:mm:ss (e.g. 1 10:17:36 for 123456 seconds). Since I could not find a suitable formatting function I did some of the work 'by hand':
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.
You can use boost date/time library for converting the time to string.
精彩评论