C标准函数库中获取时间与日期、对时间与日期数据操作及格式化

时间:2023-03-08 20:59:09
C标准函数库中获取时间与日期、对时间与日期数据操作及格式化

表示时间的三种数据类型[编辑]

  • 日历时间(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包含下列结构成员:
Member Description
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

从计算机系统时钟获得时间的方法[编辑]

  • time_t time(time_t* timer)
得到从标准计时点(一般是1970年1月1日午夜)到当前时间的秒数。
  • 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)
比较两个日历时间之差。

源代码示例[编辑]

打印当前时间到标准输出流:

# include <stdio.h>
# include <time.h> int main(void)
{
time_t timer = time(NULL);
printf("ctime is %s\n", ctime(&timer));
return 0;
}

参考来源[编辑]

  • Calendar Time. The GNU C Library Reference Manual. 2001-07-06 [2007-04-03].
  • gmtime. The Open Group Base Specifications. 2008-12-09.

外部链接[编辑]