[英]c++ - Calculate difference in time using boost::posix_time
I need help to find out the difference between two given time as string. 我需要帮助找出两个给定时间之间的差异作为字符串。 I'm using boost::posix_time and constructing the ptime object from boost::gregorian::date but i'm getting 0 when i'm trying to calculate the time_duration. 我正在使用boost :: posix_time并从boost :: gregorian :: date构造ptime对象,但是当我试图计算time_duration时我得到0。
Here is the program 这是程序
#include <boost/date_time/gregorian/gregorian.hpp>
#include "boost/date_time/posix_time/posix_time.hpp"
int main(int argc, char** argv) {
std::string date_1 = "2014-08-15 10:12:10";
std::string date_2 = "2014-08-15 16:40:02";
boost::posix_time::ptime t1(boost::gregorian::from_simple_string(date_1));
boost::posix_time::ptime t2(boost::gregorian::from_simple_string(date_2));
boost::posix_time::time_duration td = t2 - t1;
std::cout << boost::posix_time::to_simple_string(td) << std::endl;
}
This prints out 00:00:00
打印输出00:00:00
How to fix this and get the actual time duration. 如何解决此问题并获取实际持续时间。
As Martin alluded to in his comment, you used the wrong (date-only) constructor. 正如Martin在评论中提到的那样,你使用了错误的(仅限日期)构造函数。
Here is a repaired version, along with some test output: 这是一个修复的版本,以及一些测试输出:
#include <boost/date_time/gregorian/gregorian.hpp>
#include "boost/date_time/posix_time/posix_time.hpp"
int main(int argc, char** argv) {
std::string date_1 = "2014-08-15 10:12:10";
std::string date_2 = "2014-08-15 16:40:02";
boost::posix_time::ptime t1(boost::posix_time::time_from_string(date_1));
boost::posix_time::ptime t2(boost::posix_time::time_from_string(date_2));
std::cout << "t1: " << t1 << std::endl;
std::cout << "t2: " << t2 << std::endl;
boost::posix_time::time_duration td = t2 - t1;
std::cout << boost::posix_time::to_simple_string(td) << std::endl;
}
which produces the desired result: 产生预期的结果:
edd@max:/tmp$ g++ -o bdt bdt.cpp -lboost_date_time
edd@max:/tmp$ ./bdt
t1: 2014-Aug-15 10:12:10
t2: 2014-Aug-15 16:40:02
06:27:52
edd@max:/tmp$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.