2011-01-19 12 views
3

こんにちは私はブーストPosix時間システムを使用しています。私はクラスにboost :: posix_time :: time_duration to string

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

を持っていますが、タイプ

boost::posix_time::time_duration 

をto_iso_extended_string取らないだけで、これは私が後で文字列を返すようにしたいhere

を見ることができます

boost::posix_time 

を入力します出力等

どうすればこの問題を解決できますか?私は変換するブーストの方法を見ることができません

boost::posix_time::time_duration 

を文字列に変換します。私はC + +の両方に新しいので、これが本当のシンプルなものだと謝ります。

答えて

-1

boost date/timeライブラリを使用して時刻を文字列に変換できます。あなたはI/O演算子が含まれるように、むしろposix_time_types.hppよりposix_time.hppヘッダーを使用する必要があります

std::stringstream ssDuration; 
ssDuration << duration; 

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

私が探していたが、boost :: posix_time :: time_durationの機能が見つからない – Tommy

+0

ここをクリックしてください(文字列への変換):http://www.boost.org/doc/libs/1_45_0 /doc/html/date_time/posix_time.html#ptime_to_string – yasouser

+0

これが問題の原因です。これは私が使っていたものです。 "time_duration"型以外のものではないので、 "time"は "ptime"型ですが、time.time_of_day()型は "time_duration"型ですので、o_iso_extended_string(time)はokです。 – Tommy

1

あなたは< <演算子を使用して、単純みました。

5

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

注:

1

私はtime_durationでの文字列の書式設定は厄介なものだと思います。秒で指定された期間をd HH:mm:ss(たとえば、123456秒の場合は10:17:36)にフォーマットしたかったのです。私は、適切なフォーマット機能を見つけることができませんでしたので、私は "手での仕事の一部をした:

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

非常にエレガントが、私が思いついた最高ではありません。

+0

あなたの非常に便利な友人率を忘れないでください: 'int a_hours = a_duration.hours()%HOURS_PER_DAY;' – moodboom

関連する問題