C++11中輸出當前時間最直接的方法:
std::time_t t2 = std::time(nullptr); cout << std::put_time(std::localtime(&t), "%Y-%m-%d %H.%M.%S") << "." << msecs << endl;
這種方法可以輸出年月日時分秒,不過卻不能輸出毫秒,如果要輸出毫秒需要用下面的方法:
auto n = chrono::system_clock::now(); auto m = n.time_since_epoch(); auto diff = duration_cast<milliseconds>(ms).count(); auto const msecs = diff % 1000; std::time_t t = system_clock::to_time_t(n1); cout << std::put_time(std::localtime(&t), "%Y-%m-%d %H.%M.%S") << "." << msecs << endl;
將絕對時間轉換為標准時間字符串的方法:
#include <string> #include <chrono> #include <cinttypes> #include <ctime> #include <sstream> #include <iomanip> std::string millisecond_to_str(std::int64_t milliseconds) { std::chrono::milliseconds ms(milliseconds); std::chrono::time_point<std::chrono::high_resolution_clock, std::chrono::milliseconds> t1(ms); std::time_t t = std::chrono::system_clock::to_time_t(t1); std::stringstream ss; auto const msecs = ms.count() % 1000; ss << std::put_time(std::localtime(&t), "%Y-%m-%d %H.%M.%S") << "." << msecs; return ss.str(); }