自 1970 年 1 月 1 日以来经过的秒数:
time_t time1 = time(0);//这里获取到的其实就是一个long类型的时间戳,是秒级别的,非毫秒级别
time_t time1 = time(0);
cout << "time1 = " << time1 << endl;//1498122787
char * strTime = ctime(&time1);
cout << "strTime = " << strTime << endl;//Thu Jun 22 17:13:07 2017
time_t startTime = 1498122787;
double betweenSecond = difftime(time1, startTime);//该函数返回 time1 和 time2 之间相差的秒数。
cout << "betweenSecond = " << betweenSecond << endl;//Thu Jun 22 17:13:07 2017
1.时间戳转格式化
struct tm * gmtime(const time_t *timer); //将日历时间转化为世界标准时间(即格林尼治时间),并返回一个tm结构体来保存这个时间
struct tm * localtime(const time_t * timer); //将日历时间转换为本地时间,从1970年起始的时间戳转换为1900年起始的时间数据结构
time_t t = time(0);
struct tm *p;
p=gmtime(&t);
char s[100];
strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", p);
printf("%d: %s\n", (long)t, s); //1498124250: 2017-06-22 09:37:30
std::string getFormatTime() {
time_t rawTime;
struct tm* timeInfo;
char formatTime[64];
time(&rawTime);
timeInfo = localtime(&rawTime);
strftime(formatTime, sizeof(formatTime),"%Y-%m-%d %H:%M:%S",timeInfo);
return formatTime;
}
2.格式化转时间戳
long getTick(char *str_time)
{
struct tm stm;
int iY, iM, iD, iH, iMin, iS;
memset(&stm,0,sizeof(stm));
iY = atoi(str_time);
iM = atoi(str_time+5);
iD = atoi(str_time+8);
iH = atoi(str_time+11);
iMin = atoi(str_time+14);
iS = atoi(str_time+17);
stm.tm_year=iY-1900;
stm.tm_mon=iM-1;
stm.tm_mday=iD;
stm.tm_hour=iH;
stm.tm_min=iMin;
stm.tm_sec=iS;
return mktime(&stm);
}
int main()
{
char str_time[19];
printf("请输入时间:"); /*(格式:2011-12-31 11:43:07)*/
gets(str_time);
printf("%ld\n", GetTick(str_time));
return 0;
}
以上的时间都是基于秒级别的,但是我们实际应用场景中很多打印耗时都是需要获取毫秒级别的时间戳怎么办呢?
最近在看google的jni sample的时候发现了这样一段code,在此记录下:
/* Return current time in milliseconds */
static double now_ms(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec*1000. + tv.tv_usec/1000.;
}