你可以通过做整数舍入到一个句点
n = (n % period) * n;
为了使它从半个句号向上取整,只需将其抵消:
n = ((n + period/2) % period) * n;
现在改为使用time_durations。遗憾的是,我们不能直接使用 time_duration 执行 / 或 %,因此我们将首先转换为秒:
ptime round_to(ptime t, time_duration period = boost::posix_time::minutes(15)) {
auto units = (t.time_of_day() + period/2).total_seconds() / period.total_seconds();
return { t.date(), period*units };
}
看Live on Coliru
#include <boost/date_time.hpp>
using boost::posix_time::ptime;
using boost::posix_time::time_duration;
ptime round_to(ptime t, time_duration period = boost::posix_time::minutes(15)) {
auto units = (t.time_of_day() + period/2).total_seconds() / period.total_seconds();
return { t.date(), period*units };
}
int main() {
for (auto period : std::vector<time_duration> {
boost::posix_time::minutes(15),
boost::posix_time::minutes(1),
boost::posix_time::hours(1) })
{
std::cout << "-- Rounding to " << period << "\n";
for (auto timestamp: {
"2002-01-20 23:35:59.000",
"2002-01-20 23:00:59.000",
"2002-01-20 23:10:59.000",
"2002-01-20 23:55:59.000",
})
{
ptime input = boost::posix_time::time_from_string(timestamp);
std::cout << input << " -> " << round_to(input, period) << "\n";
}
}
}
打印
-- Rounding to 00:15:00
2002-Jan-20 23:35:59 -> 2002-Jan-20 23:30:00
2002-Jan-20 23:00:59 -> 2002-Jan-20 23:00:00
2002-Jan-20 23:10:59 -> 2002-Jan-20 23:15:00
2002-Jan-20 23:55:59 -> 2002-Jan-21 00:00:00
-- Rounding to 00:01:00
2002-Jan-20 23:35:59 -> 2002-Jan-20 23:36:00
2002-Jan-20 23:00:59 -> 2002-Jan-20 23:01:00
2002-Jan-20 23:10:59 -> 2002-Jan-20 23:11:00
2002-Jan-20 23:55:59 -> 2002-Jan-20 23:56:00
-- Rounding to 01:00:00
2002-Jan-20 23:35:59 -> 2002-Jan-21 00:00:00
2002-Jan-20 23:00:59 -> 2002-Jan-20 23:00:00
2002-Jan-20 23:10:59 -> 2002-Jan-20 23:00:00
2002-Jan-20 23:55:59 -> 2002-Jan-21 00:00:00