gringo
gringo

Reputation: 393

when I try to convert Boost Time_duration to string by using a sstream and facet i don't get the desired format

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.

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

Answers (1)

&#214;&#246; Tiib
&#214;&#246; Tiib

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

Related Questions