time获取当前时间
ctime——asctime 将当前获取时间转换成固定格式字符串输入
localtime —— gmtime (前者是当地时间(考虑时区)——如北京时间 ;而后者是标准时间(不考虑时区)——0时区时间)-----将time_t 转换成 struct tm *
struct tm
{
int tm_sec; /* (0 - 61) */
int tm_min; /* (0 - 59) */
int tm_hour; /* (0 - 23) */
int tm_mday; /* (1 - 31) */
int tm_mon; /* (0 - 11) */
int tm_year; /* past 1900 */
int tm_wday; /* (0 - 6) */
int tm_yday; /* (0 - 365) */
int tm_isdst; /* daylight savings flag */
};
gettimeofday——settimeday
timeval结构定义为:
struct <strong><span style="color:#ff0000;">timeval</span></strong>{
long <span style="color:#ff0000;">tv_sec</span>; /*秒*/
long <span style="color:#ff0000;">tv_usec</span>; /*微秒*/
};
timezone 结构定义为:
struct timezone{
int tz_minuteswest; /*和Greenwich 时间差了多少分钟*/
int tz_dsttime; /*日光节约时间的状态*/
};
文末有程序例子。。。
time_t time(time_t *t);
char * ctime(const time_t *timep); //返回字符串如 Thu Jul 31 22:52:40 2014
struct tm * localtime(const time_t * timep);将time_t 转换成 struct tm *,当地时间(考虑时区)——如北京时间
struct tm * gmtime(const time_t * timep);将time_t 转换成 struct tm *,标准时间(不考虑时区)——0时区时间
char * asctime(const struct tm * timeptr);------------将时间和日期以字符串格式表示 //转换字符串格式如 Thu Jul 31 15:06:27 2014 同ctime一样
asctime()将参数timeptr所指的tm结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果以字符串形态返回。此函数已经由时区转换成当地时间,字符串格式为:“Wed Jun 30 21:49:08 1993\n”
time_t mktime(strcut tm * timeptr);----------将时间结构数据转换成经过的秒数
mktime()用来将参数timeptr所指的tm结构数据转换成从公元1970年1月1日0时0分0 秒算起至今的UTC时间所经过的秒数。
================================================================================================================================
intgettimeofday(struct timeval * tv ,struct timezone * tz );-------------取得目前的时间
gettimeofday()会把目前的时间有tv所指的结构返回,当地时区的信息则放到tz所指的结构中。成功则返回0,失败返回-1
int settimeofday(const struct timeval *tv,const struct timezone *tz);-------------设置目前时间settimeofday()会把目前时间设成由tv所指的结构信息,当地时区信息则设成tz所指的结构。注意,只有root权限才能使用此函数修改时间。
程序例子:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
time_t t;
struct tm *tm;
//以time_t time(const time_t *t) 来获取当前时间,得到time_t
time(&t);//也可以用t = time(NULL);
printf("the seconds from 1970.1.1 to now: %d\n",(int)t);//time_t 其实是long 的形式,记录的是1970年以来的时间滴答数
printf("%s",ctime(&t)); //将time_t 转换成固定格式输出
tm = localtime(&t);//用time_t 构建结构体tm
printf("%04d-%02d-%02d %02d:%02d:%02d\n",tm->tm_year+1900,tm->tm_mon,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
printf("\n");
//以struct tm * time(const time_t *t) 来获取当前时间,得到time_t 和tm
tm = gmtime(&t);
printf("the seconds from 1970.1.1 to now: %d\n",(int)t);
printf("%s",asctime(tm)); //将tm 转换成固定格式输出
printf("%04d-%02d-%02d %02d:%02d:%02d\n",tm->tm_year+1900,tm->tm_mon,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
}
/*结果如下:
the seconds from 1970.1.1 to now: 1406819387
Thu Jul 31 23:09:47 2014
2014-06-31 23:09:47
the seconds from 1970.1.1 to now: 1406819387
Thu Jul 31 15:09:47 2014
2014-06-31 15:09:47
*/