前言
有时需要打印当前的绝对时间,并计算时间间隔,Unix时间戳是一种很好的时间记录标准,表示从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒。C++的标准库中并没有能够打印时间戳的方法,需要借助其它第三方库,在此记录了几种方法
正文
1、调用ctime库
#include <iostream>
#include <ctime>
int main()
{
std::time_t t = std::time(0); // t is an integer type
std::cout << t << " seconds since 01-Jan-1970\n";
return 0;
}
输出为:
1467214075 seconds since 01-Jan-1970
该方法只适用于表示以秒为单位的Unix时间戳。
2、调用chrono
#include <iostream>
#include <chrono>
int main()
{
std::chrono::milliseconds ms = std::chrono::duration_cast< std::chrono::milliseconds >(
std::chrono::system_clock::now().time_since_epoch()
);
std::cout << ms.count() << std::endl;
return 0;
}
输出以毫秒为单位的时间戳:
1644848307026
如果想得到以秒为单位的时间戳,只需将milliseconds换成seconds即可。
3、调用sys/timeb.h
#include <iostream>
#include <sys/timeb.h>
int main()
{
timeb t;
ftime(&t);
long now = t.time * 1000 + t.millitm;
std::cout << now << std::endl;
return 0;
}
输出以毫秒为单位的时间戳:
1644848305625
如果想得到以秒为单位的时间戳,需要修改成如下形式:
#include <iostream>
#include <sys/timeb.h>
int main()
{
timeb t;
ftime(&t);
int now = t.time;
std::cout << now << std::endl;
return 0;
}
输出为:
1644848308
总结
以上三种方法最终得到的都是Unix时间戳,其中以ctime库的方法使用最为简单,但只能得到以秒为单位的时间戳,具体使用看需求。
后续有其它方法再不断进行更新。