将UTCTime转换为本地时间

时间:2017-10-06 07:21:13

标签: c++11 boost

我有UTCTimeStamp Value {1507272767979279596},我想转换成人类可读的格式。

例如,

UTCTimestamp = 1507272767979279596 和 人类可读的形式是= 2017年10月6日星期五12:22:47.979 PM

C ++ STL或Boost中是否有任何函数, 这可以让我超越输出。

1 个答案:

答案 0 :(得分:1)

公平警告:你看起来有一个奇怪的时区(+05:30?)。除此之外:

<强> Live On Coliru

#include <ctime>
#include <string>

std::string usingStrftime(const time_t rawtime)
{
    struct tm * dt = localtime(&rawtime);
    char buffer[30];
    strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", dt);
    return std::string(buffer);
}

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/conversion.hpp>
#include <boost/date_time/posix_time/ptime.hpp>

boost::posix_time::ptime as_ptime(uintmax_t ns) {
    return {{1970,1,1}, boost::posix_time::microseconds(ns/1000)};
}

#include <iostream>

int main() {
    std::cout << usingStrftime(1507272767) << "\n";

    auto timestamp = as_ptime(1507272767979279596ull);

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

    std::cout.imbue(std::locale(std::cout.getloc(), new boost::posix_time::time_facet("%A %b %d, %Y %I:%M:%S %p")));
    std::cout << timestamp << "\n";
}

打印

2017-10-06 06:52:47
2017-Oct-06 06:52:47.979279
Friday Oct 06, 2017 06:52:47 AM