一 什么是时间戳
时间戳是自 1970 年 1 月 1 日(08:00:00 GMT)至当前时间的总秒数。它也被称为 Unix 时间戳(Unix Timestamp)。
定义为:从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。
二 怎么获取时间戳
既然知道了什么时间戳,大家肯定猜到了时间戳是怎么来的,对的,就是调用了time()获取到的。
三 怎么解析时间戳
解析时间戳,若要解成标准的时间戳,则可以借助gmtime_s(),(gmtime()不安全) 。若要解成当地的时间戳,则可以借助localtime_s(),(localtime()不安全) 。简单示例如下
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
time_t nowtime;
time_t timestamp = time(&nowtime);
//timestamp 和 tm是一样的,都是时间戳,是一个int64的数字
cout << timestamp << ":" << nowtime << endl;
tm localtm;
localtime_s(&localtm,×tamp);
cout << localtm.tm_year +1900 << "-" << localtm.tm_mon+1 << "-" << localtm.tm_mday << " " << localtm.tm_hour
<< ":" << localtm.tm_min << ":" << localtm.tm_sec << endl;
tm gtime;
gmtime_s(>ime, ×tamp);
cout << gtime.tm_year + 1900 << "-" << gtime.tm_mon + 1 << "-" << gtime.tm_mday << " " << gtime.tm_hour
<< ":" << gtime.tm_min << ":" << gtime.tm_sec << endl;
}
是不是很简单,跟我一开始一样,当第一次听到时间戳时,总觉得是个高大上的东西,但是当明白这个东西代表的意思后,这个问题变迎刃而解了。