2017-10-06 103 views
1

我有UTCTimeStamp值{1507272767979279596},我想將其轉換爲人類可讀的格式。將UTCTime轉換爲當地時間

例如 UTCTimestamp = 1507272767979279596 和 人類可讀的形式是=星期五,2017年10月6日12:22:47.979 PM

是有在C++ STL或升壓任何功能, 可以讓我以上輸出。

+1

'strftime'可以是溶液(可能[重複](https://stackoverflow.com/questions/ 14436462/C-時間戳到人類可讀-日期時間函數)?) – Vivick

回答

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