C语言中获取系统时间的方法

include #include #include int main() { char acLocalTime[ 19 + 1 ]; GetTime(acLocalTime); printf( "系统时间为[%s]\n", acLocalTime ); } int GetTime(char *pStr) { if(NULL == pStr) { pStr = NULL; } timet t = time(NULL); struct tm *local = localtime(&t); //YYYY-MM-DD hh:mm:ss sprintf(pStr, "%d-%d-%d %d:%d:%d", local->tmyear+1900, local->tmmon+1, local->tmmday, local->tmhour, local->tmmin, local->tm_sec); return 0; }

struct tm -- 时间结构;
time.h 定义如下:
int tmsec;
int tm
min;
int tmhour;
int tm
mday;
int tmmon;
int tm
year;
int tmwday;
int tm
yday;
int tm_isdst;

tmyear 从1900年计算,所以要加1900,
月tm
mon,从0计算,所以要加1

time(&localtime); 获取时间
localtime (&t); 转为当地时间

comments powered by Disqus