solaris/unix/linux 获取系统时间的方法--精确到年月日时分秒

来源:互联网 发布:香港 网络制式 编辑:程序博客网 时间:2024/05/21 08:37

solaris/unix/linux下获取系统时间的c语言方法——精确到年月日时分秒,可以用localtime函数,该函数在windows上也是通用的。

localtime函数如下:
表头文件 #include<time.h>
定义函数 struct tm *localtime(const time_t * timep);
函数说明 localtime()将参数timep所指的time_t结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果由结构tm返回。结构tm的定义请参考gmtime()。此函数返回的时间日期已经转换成当地时区。
返回值 返回结构tm代表目前的当地时间,可以以一定格式输出。

 

实例:

运行环境是openindiana(solaris)

wangjia@openindiana:~/project_ha/test# cat localtime.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
#define DATE_FMT "%Y-%m-%d %H:%M:%S"
int main()
{
        char szTimeStampBuf[200] = "";
        int nMaxLength = 40;
        time_t  t = 0;
        struct tm *pTM = NULL;
        int nLength = 0;
       
        time(&t);
        pTM = localtime(&t);
        nLength =  strftime(szTimeStampBuf, nMaxLength, DATE_FMT, pTM);
        //nLength = safe_sprintf(szTimeStampBuf, nMaxLength, "%s", asctime(pTM));
        szTimeStampBuf[nLength] = '\0';
        printf("szTime: %s\n", szTimeStampBuf);
        return 0;
}

编译链接:

wangjia@openindiana:~/project_ha/test# gcc -o localtime localtime.c

运行:

wangjia@openindiana:~/project_ha/test# ./localtime
szTime: 2011-10-24 14:45:27
 

 

原创粉丝点击