c++ - Boost::posix_time::ptime舍入到给定的分钟数

标签 c++ boost time

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

相关文章:

c++ - 如何在 boost HTML3 示例中向服务器发送 SIGTERM 或 SIGINT 信号?

c++ - 使用或匹配正则表达式

time - 比较格式为 HH :MM AM/PM in Lotusscript 的两个字符串字段

r - 相当于 bash 命令 **time**

Python:转换小时分钟秒的行程持续时间并仅保留分钟数

c++ - 对命令行中指定的某些文件运行 ClangTool

c++ - QWidget 的背景应用到它所有的 QWidget child

c++ - boost::filesystem::path::string() 输出的奇怪行为

c++ - 是否有 WinAPI 函数 'ExistFile' ?

c++ - 为什么 std::max 不适用于字符串文字?