2012-02-20 30 views
5

Vớithế nào để làm tròn lên đến giờ tiếp theo cho một tăng :: posix_time :: ptime

boost::posix_time::ptime aTime(time_from_string("2012-01-01 11:15:00")); 

chức năng của tôi sẽ trở lại 2012-01-01 12:00:00

hoặc trường hợp ranh giới được :

boost::posix_time::ptime boundaryTime(time_from_string("2012-01-01 23:45:00")); 

chức năng của tôi sẽ trở lại

2012-01-02 00:00:00 
+0

Có thể có số thập phân không? Bạn có muốn bỏ qua các số thập phân không? –

+0

Điều gì xảy ra nếu 'aTime' đã chính xác vào giờ? –

Trả lời

3

Đây là một ví dụ. Tôi đã giả định rằng số giây phân số nên được bỏ qua. Tôi cũng giả định rằng nếu thời gian ban đầu đã chính xác vào giờ, thì nó không cần phải tăng lên đến giờ tiếp theo.

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

namespace bpt = boost::posix_time; 

bpt::ptime roundedToNextHour(const bpt::ptime& time) 
{ 
    // Get time-of-day portion of the time, ignoring fractional seconds 
    bpt::time_duration tod = bpt::seconds(time.time_of_day().total_seconds()); 

    // Round time-of-day down to start of the hour 
    bpt::time_duration roundedDownTod = bpt::hours(tod.hours()); 

    // Construct the result with the same date, but with the rounded-down 
    // time-of-day. 
    bpt::ptime result(time.date(), roundedDownTod); 

    // If the original time was not already on the hour, add one-hour to the 
    // result. Boost knows how to handle the case where time overflows to the 
    // next day. 
    if (tod != roundedDownTod) 
     result += bpt::hours(1); 

    return result; 
} 

int main() 
{ 
    bpt::ptime aTime(bpt::time_from_string("2012-01-01 11:15:00")); 
    bpt::ptime boundaryTime(bpt::time_from_string("2012-01-01 23:45:00")); 
    bpt::ptime onTheHour(bpt::time_from_string("2012-01-01 23:00:00")); 

    std::cout << roundedToNextHour(aTime) << "\n"; 
    std::cout << roundedToNextHour(boundaryTime) << "\n"; 
    std::cout << roundedToNextHour(onTheHour) << "\n"; 
} 

Output:

2012-Jan-01 12:00:00 
2012-Jan-02 00:00:00 
2012-Jan-01 23:00:00 

Tôi hy vọng ví dụ này giúp bạn học cách Tăng Posix Thời gian hoạt động.

+0

Tôi đã thực hiện điều này bằng cách sử dụng to_tim để chuyển đổi thành cấu trúc tm. Tôi thấy nó kỳ quặc đến mức tôi không thể hỏi thời gian cho các thành phần của nó. Ví dụ của bạn cho tôi biết cách thực hiện điều đó. Cảm ơn! – John

Các vấn đề liên quan