我正试图将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;
}
我不能立即看到错误,因为它似乎正确地从时间点减去持续时间
我不知道你说的
是什么意思我不能立即看到错误,因为它似乎正确地从一个时间点减去持续时间。
我也无法看到错误,因为行为是我所期望的。当然,我不知道你在期待什么。是:
#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