gpt4 book ai didi

c++ - 从 Boost ptime 中减去分钟数

转载 作者:行者123 更新时间:2023-11-28 06:59:36 25 4
gpt4 key购买 nike

我正在尝试将 posix_time::ptime 实例限制为 5 分钟的间隔。

例如:

1.  10:31:00 -> 10:30:00 
2. 11:59:00 -> 11:55:00

我的理解是,可以根据一个周期从 ptime 中减去时间。然而,下面的代码似乎增加了时间而不是减少了它。

#include <iostream>

#include "boost/date_time.hpp"
using namespace boost::posix_time;

boost::posix_time::ptime make(int h, int m, int s)
{
return boost::posix_time::ptime
(boost::gregorian::date(1900,1,1),
boost::posix_time::time_duration(h,m,s,0));
}

int main()
{
boost::posix_time::ptime t = make(22,2,0);

int extra_mins = t.time_of_day().minutes() % 5;

t -= boost::posix_time::minutes(extra_mins);

if (t.time_of_day().minutes() != 0)
std::cout << "ERROR";

return 0;
}

我无法立即看到错误,因为它似乎正确地减少了某个时间点的持续时间。

最佳答案

我不明白你的意思

I'm not able to immediately see the error, as it seems to be correctly decrement a duration from a time point.

我也看不到错误,因为行为符合我的预期。当然,我不知道你在期待什么。开始了:

#include <iostream>
#include "boost/date_time.hpp"
#include "boost/date_time/posix_time/posix_time_io.hpp"

using namespace boost::posix_time;

boost::posix_time::ptime make(int h, int m, int s)
{
return boost::posix_time::ptime
(boost::gregorian::date(1900,1,1),
boost::posix_time::time_duration(h,m,s,0));
}

int main()
{
boost::posix_time::ptime t = make(22,2,0);
std::cout << "made: " << t << "\n";

int extra_mins = t.time_of_day().minutes() % 5;
std::cout << "extra_mins: " << extra_mins << "\n";

t -= boost::posix_time::minutes(extra_mins);
std::cout << "t - extra_mins: " << t << "\n";

if (t.time_of_day().minutes() != 0)
std::cout << "ERROR";
}

输出:

made: 1900-Jan-01 22:02:00
extra_mins: 2
t - extra_mins: 1900-Jan-01 22:00:00

我觉得还不错。参见 ti Live On Coliru 也是。

关于c++ - 从 Boost ptime 中减去分钟数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22680273/

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