以下幾種方式都是來自網(wǎng)上搜集資料的匯總掂器,對于老的方式亚皂,容易出現(xiàn)問題,比如:利用 ftime 函數(shù)的国瓮, ndk 下灭必,就不通用了,編譯不過(函數(shù)被棄用)巍膘,下面的方式都是比較通用的做法厂财,希望對大家有幫助。
方法一:
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
/*
取當前時間峡懈,精確到微秒璃饱;
*/
int main(int argc, char *argv[])
{
auto now = std::chrono::system_clock::now();
//通過不同精度獲取相差的毫秒數(shù)
uint64_t dis_millseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count()
- std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count() * 1000;
time_t tt = std::chrono::system_clock::to_time_t(now);
auto time_tm = localtime(&tt);
char strTime[25] = { 0 };
sprintf(strTime, "%d-%02d-%02d %02d:%02d:%02d %03d", time_tm->tm_year + 1900,
time_tm->tm_mon + 1, time_tm->tm_mday, time_tm->tm_hour,
time_tm->tm_min, time_tm->tm_sec, (int)dis_millseconds);
std::cout << strTime << std::endl;
strftime(tmp, sizeof(tmp), "%Y-%m-%d %X:%A", localtime(&strTime) );
printf("[%s]Tian debug LogPrint: %s\n", tmp, logConent.c_str());
return 1;
}
方法二
#include <ctime>
#include <string>
#include <chrono>
#include <sstream>
#include <iomanip>
#include <iostream>
// use strftime to format time_t into a "date time"
std::string date_time(std::time_t posix)
{
char buf[20]; // big enough for 2015-07-08 10:06:51\0
std::tm tp = *std::localtime(&posix);
return {buf, std::strftime(buf, sizeof(buf), "%F %T", &tp)};
}
std::string stamp()
{
using namespace std;
using namespace std::chrono;
// get absolute wall time
auto now = system_clock::now();
// find the number of milliseconds
auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;
// build output string
std::ostringstream oss;
oss.fill('0');
// convert absolute time to time_t seconds
// and convert to "date time"
oss << date_time(system_clock::to_time_t(now));
oss << '.' << setw(3) << ms.count();
return oss.str();
}
int main()
{
std::cout << stamp() << '\n';
}
方法三 ( 微秒 )
std::string stamp()
{
using namespace std;
using namespace std::chrono;
auto now = system_clock::now();
// use microseconds % 1000000 now
auto us = duration_cast<microseconds>(now.time_since_epoch()) % 1000000;
std::ostringstream oss;
oss.fill('0');
oss << date_time(system_clock::to_time_t(now));
oss << '.' << setw(6) << us.count();
return oss.str();
}
[圖片上傳失敗...(image-498b8d-1642079908073)]