有时需要将当前时间以一定格式输出,比如: yyyy-MM-dd HH:mm:ss,SSS。使用C++标准库有多种实现方式。
1.std::strftime
#include <chrono>
#include <string>
#include <memory>
#include <ctime>
using std::chrono::system_clock;
std::string current_time() {
system_clock::time_point tp = system_clock::now();
time_t raw_time = system_clock::to_time_t(tp);
// tm*使用完后不用delete,因为tm*是由localtime创建的,并且每个线程中会有一个
struct tm *timeinfo = std::localtime(&raw_time);
char buf[24] = {0};
// 标准c++中也可以使用"%F %X,",但VC2017中不能这样用
strftime(buf, 24, "%Y-%m-%d %H:%M:%S,", timeinfo);
// tm只能到秒,毫秒需要另外获取
std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
std::string milliseconds_str = std::to_string(ms.count() % 1000);
if (milliseconds_str.length() < 3) {
milliseconds_str = std::string(3 - milliseconds_str.length(), '0') + milliseconds_str;
}
return std::string(buf) + milliseconds_str;
}
2.std::wcsftime
#include <chrono>
#include <string>
#include <memory>
#include <ctime>
using std::chrono::system_clock;
std::wstring current_time() {
system_clock::time_point tp = system_clock::now();
time_t raw_time = system_clock::to_time_t(tp);
// tm*使用完后不用delete,因为tm*是由localtime创建的,并且每个线程中会有一个
struct tm *timeinfo = std::localtime(&raw_time);
wchar_t buf[24] = { 0 };
// 标准c++中也可以使用"%F %X,",但VC2017中不能这样用
wcsftime(buf, 24, L"%Y-%m-%d %H:%M:%S,", timeinfo);
// tm只能到秒,毫秒需要另外获取
std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
std::wstring milliseconds_str = std::to_wstring(ms.count() % 1000);
if (milliseconds_str.length() < 3) {
milliseconds_str = std::string(3 - milliseconds_str.length(), '0') + milliseconds_str;
}
return std::wstring(buf) + milliseconds_str;
}
3.std::put_time(C++11)
#include <chrono>
#include <string>
#include <memory>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
using std::chrono::system_clock;
std::string current_time1() {
system_clock::time_point tp = system_clock::now();
time_t raw_time = system_clock::to_time_t(tp);
// tm*使用完后不用delete,因为tm*是由localtime创建的,并且每个线程中会有一个
struct tm *timeinfo = std::localtime(&raw_time);
std::stringstream ss;
ss << std::put_time(timeinfo, "%Y-%m-%d %H:%M:%S,");
// tm只能到秒,毫秒需要另外获取
std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
std::string milliseconds_str = std::to_string(ms.count() % 1000);
if (milliseconds_str.length() < 3) {
milliseconds_str = std::string(3 - milliseconds_str.length(), '0') + milliseconds_str;
}
return ss.str() + milliseconds_str;
}
standard C++11 strftime format: http://en.cppreference.com/w/c/chrono/strftime
VC++2017 strftime format: https://msdn.microsoft.com/en-us/library/fe06s4ak.aspx
通过对比可以发现标准C++中的format与VC++2017中定义的format有不同之处,使用时要小心。