C/C++获取HTTP/GMT时间(gmtime)

陪她去流浪 桃子 2015年08月23日 阅读次数:3488

记录一些小的代码片段,以少造一些轮子,还是放在博客方便搜索一些~~

以下代码是用来生成 HTTP Date 头需要用到的当前 GMT 时间的代码片段。

大体代码就是这样,可能需要少许修改,比如 nullptr 需要C++11的支持,反正,按需修改吧~

#include <ctime>
#include <string>

std::string http_gmtime() {
	time_t now = time(nullptr);
	tm* gmt = gmtime(&now);

	// http://en.cppreference.com/w/c/chrono/strftime
	// e.g.: Sat, 22 Aug 2015 11:48:50 GMT
	//       5+   3+4+   5+   9+       3   = 29
	const char* fmt = "%a, %d %b %Y %H:%M:%S GMT";
	char tstr[30];

	strftime(tstr, sizeof(tstr), fmt, gmt);

	return tstr;
}

标签:HTTP