2010-11-18 32 views
0

我希望得到以下值以提前10分鐘進行日期時間。然後以這種格式返回新的日期時間:yyyy/mm/dd/HH/MMC++:提前10分鐘的日期時間實例

int yyyy = 2010; 
int month = 11; 
int day = 18; 
int hour = 12; 
int minute = 10; 

Datetime? 

回答

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

它有可能以這種格式輸出ptime yyyy/mm/dd/HH/MM?謝謝! – olidev 2010-11-18 19:39:56

+0

是的,看看Chris的迴應。他展示瞭如何以你需要的格式輸出:) – 2010-11-18 20:07:46

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 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 2010-11-18 19:41:30

+0

memset是標準的CRT功能,它到處存在。我添加了格式化字符串的答案。 – Dialecticus 2010-11-18 20:50:24

相關問題