unix timestamp to boost::posix_time::ptime

隐身守侯 提交于 2019-12-01 16:27:35

Use the from_time_t() conversion function. A time_t is a UNIX timestamp, i.e. the number of seconds since the epoch.

For a machine that has boost date/time compiled to the default level of microsecond resolution, try this:

double ts = 1250524800.5;
// Use floor() here if seconds are always positive.
time_t secondsSinceEpoch = floor(ts);
long microsecondsSinceSecond =
    floor((ts - static_cast<double>(secondsSinceEpoch)) * 1000000);
boost::posix_time::ptime result =
    boost::posix_time::from_time_t(secondsSinceEpoch);
boost::posix_time::time_duration fractionalSeconds(0, 0, 0,
                                                   microsecondsSinceSecond);
result += fractionalSeconds;
cout << "Time stamp is " << result << endl;

The output for this is "Time stamp is 2009-Aug-17 16:00:00.500000" on my linux box.

after some fiddling around i came up with this:

ptime(date(1970, 1, 1), time_duration(0, 0, 0, time_duration::ticks_per_second() * 1234567890.0987654321))

I'm not sure this is the best solution, but it seems to do what i need.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!