今天设计了一个会话管理框架,管理客户端与服务器的每个Session,在SessionMgr管理会话的时候,用到时间函数,去判断会话是否超时。这里顺便整理下,时间相关的一些函数和结构体。
一. time_t
先不关心操作系统类型,从下面声明可以看出time_t其实就是个长整型,一个日历时间,也就是从1970年1月1日0时0分0秒到此时的秒数,最迟时间是2038年1月18日19时14分07秒。
#ifndef _TIME_T_DEFINED #ifdef _USE_32BIT_TIME_T typedef __time32_t time_t; /* time value */ #else typedef __time64_t time_t; /* time value */ #endif #define _TIME_T_DEFINED /* avoid multiple def's of time_t */ #endif
time_t curTime; curTime = time(NULL); printf("Time: %d \r\n",curTime);
二.tm
time_t只是一个长整型,不符合我们的使用习惯,需要转换成本地时间,就要用到tm结构
struct tm { int tm_sec; /* seconds after the minute - [0,59] */ 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 */ 从1900年到现在的年数,所以计算当前年份的时候要在该属性基础上加上1900 int tm_wday; /* days since Sunday - [0,6] */ int tm_yday; /* days since January 1 - [0,365] */ int tm_isdst; /* daylight savings time flag */ };
用localtime获取当前系统时间:
struct tm * localtime(const time_t *)
使用gmtime函数获取格林尼治时间:
struct tm * gmtime(const time_t *)
四.示例代码:
#include "stdafx.h" #include <time.h> #include <stdlib.h> #include <iostream> using namespace std; void displaytime(const struct tm * ptm) { char *pxq[]={"日","一","二","三","四","五","六"}; cout << ptm->tm_year+1900 << "年" << ptm->tm_mon+1 << "月" << ptm->tm_mday << "日 " ; cout << ptm->tm_hour << ":" << ptm->tm_min << ":" << ptm->tm_sec <<" " ; cout << " 星期" <<pxq[ptm->tm_wday] << " 当年的第" << ptm->tm_yday << "天 " << endl; } int _tmain(int argc, _TCHAR* argv[]) { time_t curTime; curTime = time(NULL); printf("Time: %d \r\n",curTime); struct tm * localTime = localtime(&curTime); struct tm * gmTime = gmtime(&curTime); displaytime(localTime); displaytime(gmTime); system("pause"); return 0; }
输出为:
Time: 1374131485
2013年7月18日 7:11:25 星期四 当年的第198天
2013年7月18日 7:11:25 星期四 当年的第198天
请按任意键继续. . .