c语言随时间变化的函数 c语言时间随机函数( 四 )


返回经过的秒数 。
范例
/* 用time()取得时间(秒数),利用localtime()
转换成struct tm 再利用mktine()将struct tm转换成原来的秒数*/
#i nclude
main()
{
time_t timep;
strcut tm *p;
time(timep);
printf("time() : %d \n",timep);
p=localtime(timep);
timep = mktime(p);
printf("time()-localtime()-mktime():%d\n",timep);
}
执行
time():974943297
time()-localtime()-mktime():974943297
【c语言随时间变化的函数 c语言时间随机函数】
settimeofday(设置目前时间)
相关函数
time,ctime,ftime,gettimeofday
表头文件
#i nclude
#i nclude
定义函数
int settimeofday ( const struct timeval *tv,const struct timezone *tz);
函数说明
settimeofday()会把目前时间设成由tv所指的结构信息,当地时区信息则设成tz所指的结构 。详细的说明请参考gettimeofday() 。
注意,只有root权限才能使用此函数修改时间 。
返回值
成功则返回0,失败返回-1,错误代码存于errno 。
错误代码
EPERM 并非由root权限调用settimeofday(),权限不够 。
EINVAL 时区或某个数据是不正确的,无法正确设置时间 。
time(取得目前的时间)
相关函数
ctime,ftime,gettimeofday
表头文件
#i nclude
定义函数
time_t time(time_t *t);
函数说明
此函数会返回从公元1970年1月1日的UTC时间从0时0分0秒算起到现在所经过的秒数 。如果t 并非空指针的话,
此函数也会将返回值存到t指针所指的内存 。
返回值
成功则返回秒数,失败则返回((time_t)-1)值,错误原因存于errno中 。
范例
#i nclude
mian()
{
int seconds= time((time_t*)NULL);
printf("%d\n",seconds);
}
Date and Time Functions: time.h
The header time.h declares types and functions for manipulating date and time. Some functions process local time,
which may differ from calendar time, for example because of time zone. clock_t and time_t are arithmetic types
representing times, and struct tm holds the components
of a calendar time:
int tm_sec;seconds after the minute (0,61)
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
int tm_wday;days since Sunday (0,6)
int tm_yday;days since January 1 (0,365)
int tm_isdst; Daylight Saving Time flag
tm_isdst is positive if Daylight Saving Time is in effect, zero if not, and negative if the information is not available.
clock_t clock(void)
clock returns the processor time used by the program since the beginning of execution, or -1 if unavailable.
clock()/CLK_PER_SEC is a time in
seconds.
time_t time(time_t *tp)
time returns the current calendar time or -1 if the time is not available. If tp is not NULL,
the return value is also assigned to *tp.
double difftime(time_t time2, time_t time1)
difftime returns time2-time1 expressed in seconds.
time_t mktime(struct tm *tp)
mktime converts the local time in the structure *tp into calendar time in the same representation used by time.
The components will have values
in the ranges shown. mktime returns the calendar time or -1 if it cannot be represented.
The next four functions return pointers to static objects that may be overwritten by other calls.
char *asctime(const struct tm *tp)
asctime*tp into a string of the form
Sun Jan3 15:14:13 1988\n\0
char *ctime(const time_t *tp)
ctime converts the calendar time *tp to local time; it is equivalent to

推荐阅读