【问题标题】:Boost boost::posix_time::time_duration to string将 boost::posix_time::time_duration 提升为字符串
【发布时间】:2011-01-19 15:15:46
【问题描述】:

您好,我正在使用 boost Posix 时间系统。我有课

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());
}

但是 to_iso_extended_string 不带类型

boost::posix_time::time_duration

只输入

boost::posix_time

这个可以看here

我想返回一个字符串以供以后输出等

我该如何解决这个问题?我在 boost 中看不到转换方法

boost::posix_time::time_duration

到字符串。我对 C++ 和 boost 都是新手,如果这是一个真正简单的问题,我深表歉意。

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    使用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$ 
    

    请注意,您需要使用 posix_time.hpp 标头而不是 posix_time_types.hpp 来包含 I/O 运算符。

    【讨论】:

      【解决方案2】:

      您是否尝试过简单地使用

      std::stringstream ssDuration;
      ssDuration << duration;
      
      std::string str = ssDuration.str();
      

      【讨论】:

        【解决方案3】:

        我认为带有 time_duration 的字符串格式有点烦人。我想将以秒为单位的持续时间格式化为 d HH:mm:ss (例如 1 10:17:36 为 123456 秒)。由于我找不到合适的格式化函数,所以我“手动”做了一些工作:

        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());
        }
        

        不是很优雅,但我想出了最好的。

        【讨论】:

        • 别忘了你非常有用的朋友模数:int a_hours = a_duration.hours() % HOURS_PER_DAY;
        【解决方案4】:

        您可以使用boost date/time 库将时间转换为字符串。

        【讨论】:

        • 那是我一直在寻找但找不到 boost::posix_time::time_duration 的函数
        • 请看这里(转换为字符串):boost.org/doc/libs/1_45_0/doc/html/date_time/…
        • 这就是我遇到问题的地方。这就是我一直在使用的,它们不包括“time_duration”类型,所以 o_iso_extended_string(time) 可以,因为“time”属于“ptime”类型,但 time.time_of_day() 属于“time_duration”类型。跨度>
        猜你喜欢
        • 2016-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多