天天看點

C 擷取目前日期時間并轉換UNIX時間戳

擷取目前日期時間并轉換UNIX時間戳,廢話就不多講了,直接上代碼,代碼也比較簡單,隻是起到一個記錄的作用,是以代碼中就不帶注釋了.

#include <stdio.h>      /* puts */
#include <time.h>       /* time_t, struct tm, time, localtime, strftime */
#include <string>
#include <iostream>

int main ()
{
// 擷取目前日期時間
            std::string s;
            char stime[256] = { 0 };
            time_t now_time;
            time(&now_time);
            strftime(stime, sizeof(stime), "%F %H:%M:%S", localtime(&now_time));
            s = stime;
			std::cout << s << std::endl;
			
//轉換UNIX時間戳
	    struct tm tm;
            strptime(s.c_str(),"%F %H:%M:%S", &tm) ;
            time_t ft=mktime(&tm);
            int i_time = ft;
            std::cout << i_time << std::endl;
            
  return 0;
}                

運作結果:

2016-03-11 15:56:58
1457683018                

PS:

直接擷取UNIX時間戳

#include <iostream>
#include <string>
#include <sys/time.h>

int main()
{
	struct timeval tm;
	unsigned long ms;
	gettimeofday(&tm,NULL);
	ms = tm.tv_sec;
	std::cout << ms << std::endl;
	return 0;
}                

版權聲明:本文為CSDN部落客「weixin_34290390」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。

原文連結:https://blog.csdn.net/weixin_34290390/article/details/91750479