C++ 将日期时间字符串干净地转换为纪元

发布于 2024-07-20 16:11:22 字数 104 浏览 5 评论 0原文

是否有 C/C++/STL/Boost clean 方法将日期时间字符串转换为纪元时间(以秒为单位)?

yyyy:mm:dd hh:mm:ss

Is there a C/C++/STL/Boost clean method to convert a date time string to epoch time (in seconds)?

yyyy:mm:dd hh:mm:ss

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无人接听 2024-07-27 16:11:22

请参阅:日期/时间转换:字符串表示形式到 time_t

以及:< a href="http://archives.free.net.ph/message/20060504.123105.73e1c873.en.html#boost-users" rel="nofollow noreferrer">[Boost-users] [date_time] 那么为什么没有不是 to_time_t 辅助函数?

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

#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

See: Date/time conversion: string representation to time_t

And: [Boost-users] [date_time] So how come there isn't a 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();    

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.

梦忆晨望 2024-07-27 16:11:22

在 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() 来完成相同的工作。

On Windows platform you can do something like this if don't want to use 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;

If you prefer standard library, you can use struct tm and mktime() to do the same job.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文