从boost ptime中删除秒,毫秒和微秒

时间:2013-10-03 11:38:48

标签: c++ datetime boost

我想从现有的boost::posix_time::ptime构建一个新的ptime,只保留年,月,日,小时和分钟。 有没有解决方案?

编辑:感谢Rudolfs Bundulis,我找到了一个有效的解决方案:

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

using namespace boost::posix_time; 

int main()
{ 
    const ptime time(microsec_clock::local_time());
    const time_duration time_of_day = time.time_of_day(); 
    const ptime time2(time - microseconds(time_of_day.total_microseconds()) + hours(time_of_day.hours()) + minutes(time_of_day.minutes()));

    std::cout << "time 1: " << time  << std::endl;
    std::cout << "time 2: " << time2 << std::endl;
    return 0; 
}

2 个答案:

答案 0 :(得分:2)

不是100%肯定,因为我也是新手,但我认为这可以做到:

boost::posix_time::ptime time(boost::posix_time::second_clock::local_time());
boost::posix_time::time_duration time_of_day = time.time_of_day();
time_of_day -= boost::posix_time::seconds(time_of_day.seconds());
boost::posix_time::ptime time2(time.date(), time_of_day);

答案 1 :(得分:0)

要舍入到秒和毫秒(删除ms和我们的偏移量):

namespace b_pt = boost::posix_time;
// existing ptime which has to be rounded
b_pt::ptime existing_pt;

// rounding to seconds
b_pt::ptime rounded2sec(existing_pt.date(), b_pt::seconds(existing_pt.time_of_day().total_seconds()));

// rounding to milliseconds
b_pt::ptime rounded2msec(existing_pt.date(), b_pt::milliseconds(existing_pt.time_of_day().total_milliseconds));