boost c ++中的大纪元时间/时间格式

时间:2017-09-19 10:14:55

标签: c++ boost boost-date-time

在Linux中,我正在阅读" / proc / stat"作为btime,我想用c ++ boost转换为可读的日期和时间格式。

我已尝试过以下内容,日期工作正常。

    time_t btime_ = 1505790902; //This is epoch time read from "/proc/stat" file.

    std::wstring currentDate_ = L"";
    boost::gregorian::date current_date_ = 
             boost::posix_time::from_time_t(btime_).date();

    std::wstring year_ = boost::lexical_cast<std::wstring>
                                         (current_date_.year());
    std::wstring day_ = boost::lexical_cast<std::wstring>
                                         (current_date_.day());

在这里,我每年都在变得正确。但我如何从上世纪时间获得时间(HH :: MM:SS)?让我说一下 - 我可以试试。

先谢谢。

2 个答案:

答案 0 :(得分:2)

只需:

<强> Live On Coliru

System.loadLibrary

打印

#include <ctime>
#include <boost/date_time/posix_time/posix_time_io.hpp>

int main() {
    std::time_t btime_ = 1505790902; //This is epoch time read from "/proc/stat" file.

    std::cout << boost::posix_time::from_time_t(btime_) << "\n";

    std::cout.imbue(std::locale(std::cout.getloc(), new boost::posix_time::time_facet("%H:%M:%S")));
    std::cout << boost::posix_time::from_time_t(btime_) << "\n";
}

更新

评论:

<强> Live On Coliru

2017-Sep-19 03:15:02
03:15:02

打印

#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <boost/date_time/c_local_time_adjustor.hpp>

namespace pt = boost::posix_time;
namespace g  = boost::gregorian;
using local_adj = boost::date_time::c_local_adjustor<pt::ptime>;

int main() {
    std::cout.imbue(std::locale(std::cout.getloc(), new pt::time_facet("%H:%M:%S")));

    std::time_t btime_ = 1505790902; // This is epoch time read from "/proc/stat" file.

    pt::ptime const timestamp = pt::from_time_t(btime_);

    std::cout << timestamp << "\n";

    // This local adjustor depends on the machine TZ settings
    std::cout << local_adj::utc_to_local(timestamp) << " local time\n";
}

答案 1 :(得分:1)

您可以使用time_facet。这是打印UTC日期/时间的示例:

std::string PrintDateTime()
{
    std::stringstream str;
    boost::posix_time::time_facet *facet = new boost::posix_time::time_facet("%d.%m.%Y-%H:%M:%S-UTC");
    str.imbue(std::locale(str.getloc(), facet));
    str << boost::posix_time::second_clock::universal_time(); //your time point goes here
    return str.str();
}

请注意,您无需担心facet的内存管理问题。它已经从内部得到了照顾。