以下几种方式都是来自网上搜集资料的汇总,对于老的方式,容易出现问题,比如:利用 ftime 函数的, ndk 下,就不通用了,编译不过(函数被弃用),下面的方式都是比较通用的做法,希望对大家有帮助。
方法一:
1#include <stdio.h> 2#include <string.h> 3#include <sys/time.h> 4#include <iostream> 5#include <iomanip> 6#include <ctime> 7#include <chrono> 8/* 9取当前时间,精确到微秒; 10*/ 11int main(int argc, char *argv[]) 12{ 13 auto now = std::chrono::system_clock::now(); 14 //通过不同精度获取相差的毫秒数 15 uint64_t dis_millseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count() 16 - std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count() * 1000; 17 time_t tt = std::chrono::system_clock::to_time_t(now); 18 auto time_tm = localtime(&tt); 19 char strTime[25] = { 0 }; 20 sprintf(strTime, "%d-%02d-%02d %02d:%02d:%02d %03d", time_tm->tm_year + 1900, 21 time_tm->tm_mon + 1, time_tm->tm_mday, time_tm->tm_hour, 22 time_tm->tm_min, time_tm->tm_sec, (int)dis_millseconds); 23 std::cout << strTime << std::endl; 24 return 1; 25}
方法二
1#include <ctime> 2#include <string> 3#include <chrono> 4#include <sstream> 5#include <iomanip> 6#include <iostream> 7 8// use strftime to format time_t into a "date time" 9std::string date_time(std::time_t posix) 10{ 11 char buf[20]; // big enough for 2015-07-08 10:06:51\0 12 std::tm tp = *std::localtime(&posix); 13 return {buf, std::strftime(buf, sizeof(buf), "%F %T", &tp)}; 14} 15 16std::string stamp() 17{ 18 using namespace std; 19 using namespace std::chrono; 20 21 // get absolute wall time 22 auto now = system_clock::now(); 23 24 // find the number of milliseconds 25 auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000; 26 27 // build output string 28 std::ostringstream oss; 29 oss.fill('0'); 30 31 // convert absolute time to time_t seconds 32 // and convert to "date time" 33 oss << date_time(system_clock::to_time_t(now)); 34 oss << '.' << setw(3) << ms.count(); 35 36 return oss.str(); 37} 38 39int main() 40{ 41 std::cout << stamp() << '\n'; 42}
方法三 ( 微秒 )
1std::string stamp() 2{ 3 using namespace std; 4 using namespace std::chrono; 5 6 auto now = system_clock::now(); 7 8 // use microseconds % 1000000 now 9 auto us = duration_cast<microseconds>(now.time_since_epoch()) % 1000000; 10 11 std::ostringstream oss; 12 oss.fill('0'); 13 14 oss << date_time(system_clock::to_time_t(now)); 15 oss << '.' << setw(6) << us.count(); 16 17 return oss.str(); 18}
good luck