Reputation: 393
I am trying to convert a boost::posix_time::time_duration
object into a string of the form "%H%M. The problem is that the conversation is not working its as if it doesn't exist.
convert_duration_to_string
I tried this way also as illustrated in the below function. It can solve the problem. But it is so ugly. Suppose in the future we have to change the date format. In that case we will have to change the code inside the function too.
std::string convert_duration_to_string(Duration duration) {
std::ostringstream os;
os << std::setfill('0') << std::setw(2) << duration.hours()
<< std::setfill('0') << std::setw(2) << duration.minutes();
return os.str();
}
#include <boost/date_time/local_time/local_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "boost/date_time/gregorian/gregorian.hpp"
#include <iostream>
#include <sstream>
typedef boost::posix_time::time_duration Duration;
boost::posix_time::ptime parse_time_object(const std::string &time,
const std::string &format) {
std::stringstream ss;
ss << time.c_str();
ss.imbue(std::locale(
std::locale::classic(),
new boost::local_time::local_time_input_facet(format.c_str())));
boost::posix_time::ptime time_object;
ss >> time_object;
return time_object;
}
std::string convert_duration_to_string(Duration duration,
const std::string &format) {
std::ostringstream os;
os.imbue(std::locale(std::locale::classic(),
new boost::posix_time::time_facet(format.c_str())));
os << duration;
return os.str();
}
int main (){
Duration duration = parse_time_object("0740", "%H%M").time_of_day();
//[...] PLENTY OF THINGS CAN HAPPEN IN HERE THE DATE CAN GO through A
// WHOLE PIPELINE AND COME BACK
std::cout << convert_duration_to_string(duration,"%H%M") << std::endl; //Should Pring 0740. instead it is printing 07:40:00
return 0;
}
Upvotes: 1
Views: 615
Reputation: 11011
You are outputting time duration so you need to alter time duration format. Just creating time facet with default time duration format is not enough. IOW modifying your code like that ...:
std::string convert_duration_to_string(Duration duration,
const std::string &format) {
std::ostringstream os;
auto f = new boost::posix_time::time_facet(format.c_str());
f->time_duration_format(format.c_str());
os.imbue(std::locale(std::locale::classic(), f));
os << duration;
return os.str();
}
... seems to work.
Upvotes: 2