很简单的time函数,在time.h中定义,用法如下:
#include <stdio.h>
#include <time.h>
int main (void)
{
time_t timep;
time(&timep);
printf("UTC time is 0x%08x\n",timep);
timep=time(NULL);
printf("UTC time is 0x%08x\n",timep);
return 0;
}
而上述函数读取出来的是从1970年一月一日开始到现在的秒数,不方便查看,所以需要使用时间转换的函数,常用的时间转换函数如下所示:
char *ctime(const time_t *timep);//change time to string type
struct tm *gmtime(const time_t *timep);//change time to gmt(格林尼治时间) time
char *asctime(const struct tm *tm);
char *asctime_r(const struct tm *tm, char *buf);
char *ctime(const time_t *timep);
char *ctime_r(const time_t *timep, char *buf);
struct tm *gmtime(const time_t *timep);
struct tm *gmtime_r(const time_t *timep, struct tm *result);
struct tm *localtime(const time_t *timep);
struct tm *localtime_r(const time_t *timep, struct tm *result);
time_t mktime(struct tm *tm);
struct tm //use to save and show time
{
int tm_sec; /* Seconds (0-60) */
int tm_min; /* Minutes (0-59) */
int tm_hour; /* Hours (0-23) */
int tm_mday; /* Day of the month (1-31) */
int tm_mon; /* Month (0-11) */
int tm_year; /* Year - 1900 */
int tm_wday; /* Day of the week (0-6, Sunday = 0) */
int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
int tm_isdst; /* Daylight saving time */
};
上述函数中带有_r后缀的是线程安全型函数,也就是说在多线程中同时调用这些函数不会出现异常。换句话说一个类或者程序所提供的接口对于线程来说是原子操作或者多个线程之间的切换不会导致该接口的执行结果存在二义性,也就是说我们不用考虑同步的问题
┌───────────────┬───────────────┬─────────────────────────────────┐
│Interface │ Attribute │ Value │
├───────────────┼───────────────┼─────────────────────────────────┤
│asctime() │ Thread safety │ MT-Unsafe race:asctime locale │
├───────────────┼───────────────┼─────────────────────────────────┤
│asctime_r() │ Thread safety │ MT-Safe locale │
├───────────────┼───────────────┼─────────────────────────────────┤
│ctime() │ Thread safety │ MT-Unsafe race:tmbuf │
│ │ │ race:asctime env locale │
├───────────────┼───────────────┼─────────────────────────────────┤
│ctime_r(), gm‐ │ Thread safety │ MT-Safe env locale │
│time_r(), lo‐ │ │ │
│caltime_r(), │ │ │
│mktime() │ │ │
├───────────────┼───────────────┼─────────────────────────────────┤
│gmtime(), lo‐ │ Thread safety │ MT-Unsafe race:tmbuf env locale │
│caltime() │ │ │
└───────────────┴───────────────┴─────────────────────────────────┘
测试代码及运行效果:
#include <stdio.h>
#include <time.h>
int main (void)
{
time_t timep;
struct tm *tblock;
time(&timep);
printf("UTC time is 0x%08x\n",ctime(&timep));
printf("UTC time is 0x%08x\n",asctime(gmtime(&timep)));
tblock=localtime(&timep);
printf("local time is :%s\n",asctime(tblock));
printf("local time is :%s\n",ctime(&timep));
return 0;
}
运行效果
[root@wly]# ./gettime
UTC time is 0x401e4838
UTC time is 0x401e4838
local time is :Sun Jan 1 00:41:34 2012
local time is :Sun Jan 1 00:41:34 2012