【问题标题】:Boost::posix_time::ptime round to given number of minutesBoost::posix_time::ptime 循环到给定的分钟数
【发布时间】:2020-07-08 14:07:25
【问题描述】:

我想将分钟四舍五入到给定的步骤(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"  

boost 中是否有这样做的功能?或者如果没有,那里有实现吗?

【问题讨论】:

  • 确定最后一个例子应该延续到 2002-02-21 吗?
  • 在您接受答案后已修复。

标签: c++ boost time


【解决方案1】:

你可以通过做整数舍入到一个句点

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    相关资源
    最近更新 更多