工学1号馆

home

C标准库time.h实现

Wu Yudong    September 23, 2015     C   614   

本文主要介绍C标准库<time.h>实现

本文地址:http://wuyudong.com/archives/957,转载请注明源地址。

日期和时间

time.h是C标准函数库中获取时间与日期、对时间与日期数据操作及格式化的头文件。

时间的构成

头文件<time.h>定义了两个宏,声明了四种类型和几个操作时间的函数。

定义的宏有:NULL和CLOCKS_PER_SEC,具体如下:

#define CLOCKS_PER_SEC    60    //常设置为60HZ
#define NULL    ((void *)0)

声明的类型有:size_t和time_t,具体如下:

typedef unsigned int size_t;
typedef long time_t;        /* time in sec since 1 Jan 1970 0000 GMT */

表示时间的三种数据类型:

  • 日历时间(calendar time),是从一个标准时间点(epoch)到现在的时间经过的秒数,不包括插入闰秒对时间的调整。开始计时的标准时间点,各种编译器一般使用1970年1月1日0时0秒。日历时间用数据类型time_t表示。time_t类型实际上一般是32位或64位整数类型。
  • 时钟滴答数(clock tick),从进程启动开始计时,因此这是相对时间。每秒钟包含CLOCKS_PER_SEC(time.h中定义的常量,一般为1000)个时钟滴答。时钟滴答数用数据类型clock_t表示。clock_t类型一般是32位整数类型。
  • 分解时间(broken-down time),用结构数据类型tm表示,tm包含下列结构成员:
成员 描述
int tm_hour hour (0 – 23)
int tm_isdst 夏令时 enabled (> 0), disabled (= 0), or unknown (< 0)
int tm_mday day of the month (1 – 31)
int tm_min minutes (0 – 59)
int tm_mon month (0 – 11, 0 = January)
int tm_sec seconds (0 – 60, 60 = Leap second)
int tm_wday day of the week (0 – 6, 0 = Sunday)
int tm_yday day of the year (0 – 365)
int tm_year year since 1900

时间操纵函数

从计算机系统时钟获得时间的方法

从标准计时点(一般是1970年1月1日午夜)到当前时间的秒数:

time_t time(time_t* timer)

从进程启动到此次函数调用的累计的时钟滴答数。三种时间日期数据类型的转换函数:

clock_t clock(void)

三种时间日期数据类型的转换函数

  • struct tm* gmtime(const time_t* timer)
从日历时间time_t到分解时间tm的转换。函数返回的是一个静态分配的tm结构存储空间,该存储空间被gmtimelocaltimectime函数所共用. 这些函数的每一次调用会覆盖这块tm结构存储空间的内容。
  • struct tm* gmtime_r(const time_t* timer, struct tm* result)
该函数是gmtime函数的线程安全版本.
  • struct tm* localtime(const time_t* timer)
从日历时间time_t到分解时间tm的转换,即结果数据已经调整到本地时区与夏令时。
  • time_t mktime(struct tm* ptm)
从分解时间tm到日历时间time_t的转换。
  • time_t timegm(struct tm* brokentime)
从分解时间tm(被视作UTC时间,不考虑本地时区设置)到日历时间time_t的转换。该函数较少被使用。

时间日期数据的格式化函数

  • char *asctime(const struct tm* tmptr)
把分解时间tm输出到字符串,结果的格式为”Www Mmm dd hh:mm:ss yyyy”,即“周几 月份数 日数 小时数:分钟数:秒钟数 年份数”。函数返回的字符串为静态分配,长度不大于26,与ctime函数共用。函数的每次调用将覆盖该字符串内容。
  • char* ctime(const time_t* timer)
把日历时间time_t timer输出到字符串,输出格式与asctime函数一样.
  • size_t strftime(char* s, size_t n, const char* format, const struct tm* tptr)
把分解时间tm转换为自定义格式的字符串,类似于常见的字符串格式输出函数sprintf
  • char * strptime(const char* buf, const char* format, struct tm* tptr)
strftime的逆操作,把字符串按照自定义的格式转换为分解时间tm

对时间数据的操作

  • double difftime(time_t timer2, time_t timer1)
比较两个日历时间之差。

如果文章对您有帮助,欢迎点击下方按钮打赏作者

Comments

No comments yet.
To verify that you are human, please fill in "七"(required)