给出一个提升:: posix_time :: ptime如何向下舍入到下一个小时

Joh*_*ohn 5 boost

特定

boost::posix_time::ptime aTime( time_from_string("2012-01-01 11:15:00"));
Run Code Online (Sandbox Code Playgroud)

我的功能将返回2012-01-01 12:00:00

或给定边界情况:

boost::posix_time::ptime boundaryTime( time_from_string("2012-01-01 23:45:00"));
Run Code Online (Sandbox Code Playgroud)

我的功能将返回

2012-01-02 00:00:00
Run Code Online (Sandbox Code Playgroud)

Emi*_*ier 4

这是一个例子。我认为应该忽略小数秒。我还假设,如果原始时间已经精确到整点,则不需要增加到下一小时。

#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";
}
Run Code Online (Sandbox Code Playgroud)

输出:

2012-Jan-01 12:00:00
2012-Jan-02 00:00:00
2012-Jan-01 23:00:00
Run Code Online (Sandbox Code Playgroud)

我希望这个例子能帮助您了解 Boost Posix Time 的工作原理。