我想将分钟数舍入到给定的步骤(15分钟)。像这样
"2002-01-20 23:35:59.000" -> "2002-01-20 23:30:00.000"
"2002-01-20 23:00:59.000" -> "2002-01-20 23:00:00.000"
"2002-01-20 23:10:59.000" -> "2002-01-20 23:15:00.000"
"2002-01-20 23:55:59.000" -> "2002-02-21 00:00:00.000"
有增强功能吗?否则,是否有实现的方法?
最佳答案
您可以执行以下操作将整数舍入为一个整数
n = (n % period) * n;
要使它从半个周期开始舍入,只需将其抵消:n = ((n + period/2) % period) * n;
现在,使用time_duration
代替。遗憾的是,我们无法直接使用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
关于c++ - Boost::posix_time::ptime舍入到给定的分钟数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62796703/