`
dewei
  • 浏览: 163276 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

C风格日期时间在std c++中使用备忘

阅读更多
//包含的头文件
#include <ctime>
#include <iostream>
#include <iomanip>

 

/*{{{ 显示100个月前的时间 */
	std::time_t now = std::time(NULL);
	std::tm tm = *std::localtime(&now);//Unix时间戳转成结构
	std::cout << "Today is           " << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") << std::endl;
	//Today is           2013-10-25 17:12:56
	tm.tm_mon -= 100;
	std::time_t ago = std::mktime(&tm); //结构转成Unix时间戳

	std::cout << "100 months ago was " << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") << std::endl;
	//100 months ago was 2005-06-25 17:12:56
	/*}}} */

	/*{{{ 计算两个时间相关多少秒 */
	std::time_t start = std::time(NULL);
	volatile double d = 0.0;
	for(int n=0; n<10000; ++n)
		for(int m=0; m<100000; ++m)
			d += d*n*m; // some time-consuming operation
	std::cout << "Wall time passed: "
		<< std::difftime(std::time(NULL), start) << " s." << std::endl;
	/*}}} */

	/*{{{ 标准C++格式化时间范例
	 */
	std::time_t result = std::time(NULL);//当前Unix时间戳
	char szbuffer[32] = {0};
	std::strftime(szbuffer, sizeof(szbuffer), "%Y-%m-%d %H:%M:%S", std::localtime(&result));
	std::cout << szbuffer << std::endl;//2013-10-25 16:59:28
	/*}}} */

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics