2017-06-17 98 views
1

我試圖解決由daymonthyeardays_to_add,加days_to_add給出的日期給定日期的問題。增加持續時間時間點沒有任何影響

我能夠將日期轉換爲std::chrono::time_point<system_clock, ...>。現在我想給它添加幾天:

template <typename Clock, typename Duration> 
auto add_days(const std::chrono::time_point<Clock, Duration>& timepoint, 
                int days_to_add) 
{ 
    constexpr unsigned int seconds_in_day = 60 * 60 * 24; 
    //          mm hh dd 

    return timepoint + Duration(seconds_in_day * days_to_add); 
} 

但是結果不變timepoint。下面是完整的程序重現:

#include <iostream> 
#include <chrono> 
#include <iomanip> 

template <typename Clock, typename Duration> 
std::ostream& operator<<(std::ostream& os, const std::chrono::time_point<Clock, Duration>& timep) 
{ 
    auto converted_timep = Clock::to_time_t(timep); 
    os << std::put_time(std::localtime(&converted_timep), "%Y %b %d %H:%M:%S"); 
    return os; 
} 

template <typename Clock, typename Duration> 
auto add_days(const std::chrono::time_point<Clock, Duration>& timepoint, 
                int days_to_add) 
{ 
    constexpr unsigned int seconds_in_day = 60 * 60 * 24; 
    //          mm hh dd 

    return timepoint + Duration(seconds_in_day * days_to_add); 
} 

int main() 
{ 
    auto today = std::chrono::system_clock::now(); 
    auto tomorrow = add_days(today, 1); 
    std::cout << tomorrow; 

    return 0; 
} 

Wandbox鏈接gccclang

2017 Jun 17 16:23:18 
2017 Jun 17 16:23:18 
+0

感謝錯字修復,更名爲變量發佈前,在這裏做了一個錯字,該wandbox代碼是正確的。 – Incomputable

+1

我剛剛重現了VS2013中的錯誤(直到我做了一些修改才能夠編譯它)。我看到,'time_point'的內部數據如何變化,但'tomorrow'仍然是'今天'。我的第一個猜測:'持續時間'不需要幾秒鐘的時間。 (因此,'60 * 60 * 24'不是一天,但持續時間要短得多。) – Scheff

回答

3

的問題是,std::system_clock不存儲它的時間(秒),也不以毫秒爲單位。你認爲微秒?不。它的存儲時間爲納秒(至少在gcc上,你似乎也在使用它)!實際上,時間是由實施定義的,所以最好使用便攜式解決方案,如最後一個。

你只會認爲時間點沒有變化,但實際上,它是,但時間尺度方式小於毫秒。

如果你計算每天納秒,你會得到正確的答案:

template <typename Clock, typename Duration> 
auto add_days(const std::chrono::time_point<Clock, Duration>& timepoint, 
                int days_to_add) 
{ 
    constexpr auto nano_seconds_in_day = 1'000'000'000ul * 60 * 60 * 24; 
    //          (ns in s)  mm hh dd 

    return timepoint + Duration(nano_seconds_in_day * days_to_add); 
} 

但是如果你從std::system_clock傳遞一個時間點只會工作。其他時鐘可以有不同的duration,因此需要添加不同的值。你應該使用這個版本而不是(這是很清晰):

<typename Clock, typename Duration> 
auto add_days(const std::chrono::time_point<Clock, Duration>& timepoint, 
                int days_to_add) 
{ 
    return timepoint + 24h * days_to_add; 
} 
+1

是的,應該寫'std :: chrono :: seconds(seconds_in_day * days_to_add);',我的不好。感謝你的回答。 – Incomputable

+0

我不認爲'std :: steady_clock'需要有一個納秒的時間段 –

+0

@PserserBy Jup,你是對的。提到了這一點。謝謝:) – Rakete1111