unix time stamp翻譯爲時間戳, 就是從1970年1月1日00:00::00以來的秒數。
環境:Linux C
#include<iostream>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
int main(){
struct timeval tv;
gettimeofday(&tv,NULL);
printf("second:%ld\n",tv.tv_sec); //秒
printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒
printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec); //微秒
sleep(3); // 爲方便觀看,讓程序睡三秒後對比
std::cout << "3s later:" << std::endl;
gettimeofday(&tv,NULL);
printf("second:%ld\n",tv.tv_sec); //秒
printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒
printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec); //微秒
return 0;
}
環境:Linux C++11
秒時間戳 使用了time.h
毫秒時間戳使用了 c++11 標準庫: std::chrono
#include <time.h>
#include <chrono>
#include <iostream> // std::cout
std::time_t getTimeStamp()
{
std::chrono::time_point<std::chrono::system_clock,std::chrono::milliseconds> tp = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());//獲取當前時間點
std::time_t timestamp = tp.time_since_epoch().count(); //計算距離1970-1-1,00:00的時間長度
return timestamp;
}
int main(){
time_t timestamp;
std::cout << time(×tamp) << std::endl;//秒級時間戳
timestamp = getTimeStamp();
std::cout << timestamp << std::endl;//毫秒級時間戳
}
std::string strSystime="";
time_t systime=time(NULL);
stringstream ss;
ss<<systime;
strSystime=ss.str();
std::cout << strSystime << std::endl;