获取当前日期时间并转换UNIX时间戳,废话就不多讲了,直接上代码,代码也比较简单,只是起到一个记录的作用,所以代码中就不带注释了.
1#include <stdio.h> /* puts */ 2#include <time.h> /* time_t, struct tm, time, localtime, strftime */ 3#include <string> 4#include <iostream> 5 6int main () 7{ 8// 获取当前日期时间 9 std::string s; 10 char stime[256] = { 0 }; 11 time_t now_time; 12 time(&now_time); 13 strftime(stime, sizeof(stime), "%F %H:%M:%S", localtime(&now_time)); 14 s = stime; 15 std::cout << s << std::endl; 16 17//转换UNIX时间戳 18 struct tm tm; 19 strptime(s.c_str(),"%F %H:%M:%S", &tm) ; 20 time_t ft=mktime(&tm); 21 int i_time = ft; 22 std::cout << i_time << std::endl; 23 24 return 0; 25}
运行结果:
12016-03-11 15:56:58 21457683018
PS:
直接获取UNIX时间戳
1#include <iostream> 2#include <string> 3#include <sys/time.h> 4 5int main() 6{ 7 struct timeval tm; 8 unsigned long ms; 9 gettimeofday(&tm,NULL); 10 ms = tm.tv_sec; 11 std::cout << ms << std::endl; 12 return 0; 13}