2010-11-18 14 views

答えて

6

Boost :: Date_Timeをチェックしてください。

http://www.boost.org/doc/libs/1_44_0/doc/html/date_time.html

編集:ここではhttp://www.boost.org/doc/libs/1_36_0/doc/html/date_time/examples.htmlからの例を示します。ここで

/* Some simple examples of constructing and calculating with times 
    * Output: 
    * 2002-Feb-01 00:00:00 - 2002-Feb-01 05:04:02.001000000 = -5:04:02.001000000 
    */ 

    #include "boost/date_time/posix_time/posix_time.hpp" 
    #include <iostream> 

    int 
    main() 
    { 
    using namespace boost::posix_time; 
    using namespace boost::gregorian; 

    date d(2002,Feb,1); //an arbitrary date 
    //construct a time by adding up some durations durations 
    ptime t1(d, hours(5)+minutes(4)+seconds(2)+millisec(1)); 
    //construct a new time by subtracting some times 
    ptime t2 = t1 - hours(5)- minutes(4)- seconds(2)- millisec(1); 
    //construct a duration by taking the difference between times 
    time_duration td = t2 - t1; 

    std::cout << to_simple_string(t2) << " - " 
       << to_simple_string(t1) << " = " 
       << to_simple_string(td) << std::endl; 

    return 0; 
    } 
+0

yyyy/mm/dd/HH/MMの形式でptimeを出すことは可能ですか?ありがとうございました! – olidev

+0

はい、私の下でクリスの反応を見てください。彼はあなたが必要な形式で出力する方法を示しています:) –

2
#include <boost/date_time.hpp> 
#include <iostream> 
#include <sstream> 
#include <locale> 

int main(int argc, char* argv[]) 
{ 
    int yyyy = 2010; 
    int month = 11; 
    int day = 18; 
    int hour = 12; 
    int minute = 10; 

    boost::gregorian::date date(yyyy, month, day); 
    boost::posix_time::ptime time(date, 
     boost::posix_time::hours(hour) + 
     boost::posix_time::minutes(minute) 
    ); 

    boost::posix_time::time_facet* facet = new boost::posix_time::time_facet(); 
    facet->format("%Y/%m/%d/%H/%M"); 

    std::ostringstream oss; 
    oss.imbue(std::locale(oss.getloc(), facet)); 
    oss << time; 

    std::cout << oss.str() << std::endl; 
} 
1

うまくいくかもしれないコードの一部です。使用する関数の詳細については、MSDNを参照してください。 structをゼロで埋めることを忘れないでください。

struct tm now; 
memset(&now, 0, sizeof(struct tm)); 

now.tm_year = 2010 - 1900; // years start from 1900 
now.tm_mon = 11 - 1; // Months start from 0 
now.tm_mday = 18; 
now.tm_hour = 12; 
now.tm_min = 10; // you have day here, but I guess it's minutes 

time_t afterTime = mktime(&now) + 10 * 60; // time_t is time in seconds 

struct tm *after = localtime(&afterTime); 

編集:私はそれはそうだCおよびないC++、時には人々はちょうどソリューションを必要とし、それがどこから来たものをライブラリ気にしないので、文字列に日時を書き込むための関数を書くことを躊躇。だから:

char output[17]; // 4+1+2+1+2+1+2+1+2 format +1 zero terminator 
if (strftime(output, sizeof(output), "%Y/%m/%d/%H/%M", after) == 0) 
    handle_error(); 
+0

memsetはUbuntuでの実行にも対応していますか? yyyy/mm/dd/HH/MM?の形式でこのような出力を行うことは可能ですか?ありがとう – olidev

+0

memsetは標準的なCRT関数です、それはどこにでも存在します。私は答えの文字列にformatingを追加しました。 – Dialecticus