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

include <time.h> #include <stdlib.h> #include <stdio.h> int main() { char acLocalTime[ 19 + 1 ]; GetTime(acLocalTime); printf( "系统时间为[%s]\n", acLocalTime ); } int GetTime(char *pStr) { if(NULL == pStr) { pStr = NULL; } time_t t = time(NULL); struct tm *local = localtime(&t); //YYYY-MM-DD hh:mm:ss sprintf(pStr, "%d-%d-%d %d:%d:%d", local->tm_year+1900, local->tm_mon+1, local->tm_mday, local->tm_hour, local->tm_min, local->tm_sec); return 0; }

struct tm -- 时间结构;
time.h 定义如下:
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;

tm_year 从1900年计算,所以要加1900,
月tm_mon,从0计算,所以要加1

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

comments powered by Disqus