[C/C++标准库]_[初级]_[使用时间库]


clock

ctime

difftime

gmtime

localtime

mktime

strftime

time


场景:

1. 时间运算,显示时间等,


代码:

#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include <iostream>

using namespace std;

void TestTime()
{
	//time_t
	//For historical reasons, 
	//it is generally implemented as an integral value representing 
	//the number of seconds elapsed since 
	//00:00 hours, Jan 1, 1970 UTC (i.e., a unix timestamp). 
	//Although libraries may implement this type using alternative time representations.
	time_t t;
	time(&t);
	//快速输出时间日期,也是静态返回.
	char* str_time = ctime(&t);
	//Www Mmm dd hh:mm:ss yyyy
	cout << "str_time: " << str_time << endl;
	//1.静态返回值.
	//2.Coordinated Universal Time (usually Greenwich mean time), 
	struct tm* tt = gmtime(&t);
	struct tm t_utc = *tt;
        //1.格式化时间日期输出
	char str[32];
	memset(str,0,sizeof(str));
	size_t res = strftime(str,sizeof(str),"%Y-%m-%d %H:%M:%S",&t_utc);
	assert(res);
	cout << str << endl;

	//本地时间
	tt = localtime(&t);
	struct tm t_local = *tt;

	memset(str,0,sizeof(str));
	res = strftime(str,sizeof(str),"%Y-%m-%d %H:%M:%S",&t_local);
	assert(res);
	cout << str << endl;

	//1.UTC和本地时间差,秒.
	time_t t1 = mktime(&t_utc);
	time_t t2 = mktime(&t_local);
	double dur = difftime(t2,t1);
	cout << "duration seconds: " << dur  << " hours: " << dur / 3600 << endl;

	//1.处理器时间
	//The clock() function returns the processor time since the program started
	clock_t c1 = clock();
	cout << "c1: " << c1 << endl;
	//转换为秒.
	double cs = c1 / (double)CLOCKS_PER_SEC;
	cout << "cs: " << cs << endl;	

}

int main(int argc, char const *argv[])
{
	/* code */
	cout << "TestFormatTime" << endl;
	TestTime();
	return 0;
}

输出:

TestFormatTime
str_time: Sat Feb 08 13:43:30 2014

2014-02-08 05:43:30
2014-02-08 13:43:30
duration seconds: 28800 hours: 8
c1: 3
cs: 0.003
[Finished in 1.6s]


你可能感兴趣的:(C++,时间格式化,时间处理,time_t,标准时间库)