自 1970 年 1 月 1 日以來經(jīng)過的秒數(shù):
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);//該函數(shù)返回 time1 和 time2 之間相差的秒數(shù)餐茵。
cout << "betweenSecond = " << betweenSecond << endl;//Thu Jun 22 17:13:07 2017
1.時間戳轉(zhuǎn)格式化
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
2.格式化轉(zhuǎn)時間戳
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;
}