C++时间和日期 time.h

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013043408/article/details/83615582

time.h是C的标准库。C++继承它后,改了个马甲,成了ctime。

一些基础api。有些api是不安全的,Vs会提醒你使用安全的api。

time_t time(time_t *time);    //返回自1970起,经过了多少秒

//time_t 与 tm 的转换
struct tm *localtime(const time_t *time);  //time_t 转 本地时间
struct tm *gmtime(const time_t *time);     //time_t 转 伦敦时间
time_t mktime(struct tm *time);            //tm 转 time_t

//转字符串
char *ctime(const time_t *time);           //time_t 转 字符串, 固定格式:星期 月 日 时:分:秒 年,歪果仁看着习惯
char *asctime (const struct tm* time);     //tm 转 字符串, 固定格式:星期 月 日 时:分:秒 年,中国人看不习惯
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr);
                                           //tm 转 自定义格式的字符串,很实用。

clock_t clock(void);                             //程序自执行起,经过了多少毫秒,很实用。
double difftime ( time_t time2, time_t time1 );  //返回time2-time1,结果可以为负,很鸡肋。

//tm结构体,还是了解了解。
struct tm
{
    int tm_sec;   // seconds after the minute - [0, 60] including leap second:秒。
    int tm_min;   // minutes after the hour - [0, 59]:分。
    int tm_hour;  // hours since midnight - [0, 23]:时。
    int tm_mday;  // day of the month - [1, 31]:日。
    int tm_mon;   // months since January - [0, 11]:月。
    int tm_year;  // years since 1900:年。
    int tm_wday;  // days since Sunday - [0, 6]:星期几,0代表星期日,1代表星期一。
    int tm_yday;  // days since January 1 - [0, 365]:今天为今年的第几天。
    int tm_isdst; // daylight savings time flag:夏令时的标志。
};

夏令时的标志,感兴趣可以百度一下

获取当前日期和时间,格式:%Y-%m-%d %H:%M:%S

string GetDateTime()
{
	//%Y-%m-%d %H:%M:%S	
	time_t second;	
	time(&second); 
		
	tm localTm;	
	localtime_s(&localTm, &second); 	
	
	char localTimeStr[128] = { 0 };	
	strftime(localTimeStr, sizeof(localTimeStr), "%Y-%m-%d %H:%M:%S", &localTm);
	 	
	return localTimeStr;
}

获取当前时间,格式:%H:%M:%S

string GetTime()
{	
	//%H:%M:%S	
	time_t second;	
	time(&second); 	
	
	tm localTm;	
	localtime_s(&localTm, &second); 	

	char localTimeStr[128] = { 0 };	
	strftime(localTimeStr, sizeof(localTimeStr), "%X", &localTm); 	

	return localTimeStr;
}

计算代码块耗时,精确到毫秒

clock_t GetTimeSpaceMs()
{	
	//CLOCKS_PER_SEC	
	static clock_t oldTime = 0; 	
	clock_t newTime = clock();	
	clock_t space = newTime - oldTime;
			
	if (space < 0)	
	{		
		space = LONG_MAX + space;	
	} 
		
	oldTime = newTime;	
	return space;
}

猜你喜欢

转载自blog.csdn.net/u013043408/article/details/83615582