gpt4 book ai didi

boost - 给定 boost::posix_time::ptime 如何四舍五入到下一小时

转载 作者:行者123 更新时间:2023-12-04 20:52:01 26 4
gpt4 key购买 nike

给定的

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

我的函数将返回 2012-01-01 12:00:00

或给定边界情况:
boost::posix_time::ptime boundaryTime( time_from_string("2012-01-01 23:45:00"));

我的函数会返回
2012-01-02 00:00:00

最佳答案

这是一个例子。我假设应该忽略小数秒。我还假设如果原始时间已经正好在整点,那么它不需要增加到下一小时。

#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";
}

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

我希望这个例子能帮助你了解 Boost Posix Time 是如何工作的。

关于boost - 给定 boost::posix_time::ptime 如何四舍五入到下一小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9366683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com