且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++将Datetime字符串转换为Epoch Cleanly

更新时间:2023-11-05 17:55:46

p>请参阅:日期/时间转换:字符串表示为time_t

And: [Boost-users] [date_time]那么怎么没有一个to_time_t helper func?

所以,显然这样的东西应该工作:

So, apparently something like this should work:

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

std::string ts("2002-01-20 23:59:59");
ptime t(time_from_string(ts));
ptime start(gregorian::date(1970,1,1)); 
time_duration dur = t - start; 
time_t epoch = dur.total_seconds();    

但我不认为它比 Rob的建议:使用 sscanf 来解析数据转换成 struct tm ,然后调用 mktime

But I don't think it's much cleaner than Rob's suggestion: use sscanf to parse the data into a struct tm and then call mktime.