首页 > 学院 > 开发设计 > 正文

获取当前时间

2019-11-06 07:29:56
字体:
来源:转载
供稿:网友
获取时间的函数time()提供了秒级的精确度1、头文件 <time.h> 2、函数原型 time_t time(time_t *t) 函数返回从Epoch(00:00:00 1970-01-01 UTC)开始到现在的秒数,如果t是空指针,直接返回当前时间。如果t不是空指针,返回当前时间的同时,将返回值赋予t指向的内存空间。time_t结合localtime、gmtime、asctime、ctime可以获得当地时间或标准时间。struct tm *localtime(const time_t *clock);struct tm *gmtime(const time_t *timeptr)localtime是把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间,而gmtime函数转换后的时间没有经过时区变换,是UTC时间(格林尼治时间GMT)。char* asctime (const struct tm * timeptr)把timeptr指向的tm结构体中储存的时间转换为字符串,返回的字符串格式为:Www Mmm dd hh:mm:ss yyyy。其中Www为星期;Mmm为月份;dd为日;hh为时;mm为分;ss为秒;yyyy为年份。char *ctime(const time_t *time);把日期和时间转换为字符串其中tm结构在time.h中的定义如下:struct tm{   int tm_sec;            //取值[0,59),非正常情况下可到达61   int tm_min;            //取值同上   int tm_hour;            //取值[0,23)   int tm_mday;            //取值(1,31]   int tm_mon;            //取值[0,11)   int tm_year;            //1900年起距今的年数   int tm_wday;            //取值[0,6]   int tm_yday;            //取值[0,366)   int tm_isdst;            //夏令时标志};另外,还有一个CTime类的对象表示的时间是基于格林威治标准时间(GMT)的。CTimeSpan类的对象表示的是时间间隔。CTime类一般不会被继承使用。其对象的大小是8个字节。CTime表示的日期上限是2038年1月18日,下限是1970年1月1日 12:00:00 AM GMT。如果需要更高的时间精确度,就需要struct timespec 和 struct timeval来处理。typedef long time_t;#ifndef _TIMESPEC#define _TIMESPECstruct timespec {time_t tv_sec; // seconds long tv_nsec; // and nanoseconds };#endifstruct timespec有两个成员,一个是秒,一个是纳秒, 所以最高精确度是纳秒。一般由函数int clock_gettime(clockid_t, struct timespec *)获取特定时钟的时间,常用如下4种时钟:CLOCK_REALTIME 统当前时间,从1970年1.1日算起CLOCK_MONOTONIC 系统的启动时间,不能被设置CLOCK_PROCESS_CPUTIME_ID 本进程运行时间CLOCK_THREAD_CPUTIME_ID 本线程运行时间struct timeval {time_t tv_sec; // seconds long tv_usec; // microseconds };struct timezone{ int tz_minuteswest; //miniutes west of Greenwich int tz_dsttime; //type of DST correction };struct timeval有两个成员,一个是秒,一个是微秒, 所以最高精确度是微秒。一般由函数int gettimeofday(struct timeval *tv, struct timezone *tz)获取系统的时间 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表