是否有将日期时间字符串转换为纪元时间(以秒为单位)的C / C ++ / STL / Boost清理方法?
yyyy:mm:dd hh:mm:ss
答案 0 :(得分:10)
请参阅:Date/time conversion: string representation to time_t
并且:[Boost-users] [date_time] So how come there isn't a to_time_t helper func?
所以,显然这样的事情应该有效:
#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's suggestion更清晰:使用sscanf
将数据解析为struct tm
,然后调用mktime
。
答案 1 :(得分:3)
在Windows平台上,如果不想使用Boost,可以执行以下操作:
// parsing string
SYSTEMTIME stime = { 0 };
sscanf(timeString, "%04d:%02d:%02d %02d:%02d:%02d",
&stime.wYear, &stime.wMonth, &stime.wDay,
&stime.wHour, &stime.wMinute, &stime.wSecond);
// converting to utc file time
FILETIME lftime, ftime;
SystemTimeToFileTime(&stime, &lftime);
LocalFileTimeToFileTime(&lftime, &ftime);
// calculating seconds elapsed since 01/01/1601
// you can write similiar code to get time elapsed from other date
ULONGLONG elapsed = *(ULONGLONG*)&ftime / 10000000ull;
如果您更喜欢标准库,可以使用struct tm和mktime()来完成相同的工作。
答案 2 :(得分:1)