【发布时间】:2023-03-18 14:20:02
【问题描述】:
是否有 C/C++/STL/Boost clean 方法将日期时间字符串转换为纪元时间(以秒为单位)?
yyyy:mm:dd hh:mm:ss
【问题讨论】:
是否有 C/C++/STL/Boost clean 方法将日期时间字符串转换为纪元时间(以秒为单位)?
yyyy:mm:dd hh:mm:ss
【问题讨论】:
见: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。
【讨论】:
在 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() 来做同样的工作。
【讨论】:
【讨论】: