浅析Linux中的时间编程和实现原理(一) Linux应用层的时间编程
固定格式转换 用户指定格式转换函数。 固定格式转换 用 ctime() 函数转换出来的时间格式是系统固定的,调用者无法改动,因此被称为固定格式转换。如果您对日期格式没有特殊的要求,那么用它基本上就可以了,简单,不用记忆很多的参数。 用户指定格式转换 典型的 ctime() 格式如下: Wed Dec 7 20:45:43 PST 2011 有些人觉得这个格式太长,类似 Wed,星期三这样的信息很多情况下都没有啥用途。人们可能更喜欢其他格式:比如2011-12-07 20:45。在这种情况下,就需要进行时间显示格式转换。做法为:先把从内核得到的时间值转换为 struct tm 类型的值,然后调用 strftime() 等函数来输出自定义的时间格式字符串。 下面我列举一些实例,以便读者更清晰地理解众多的时间转换函数的用法。 各标准 C 时间转换函数的解释和举例 char *ctime(const time_t *clock); 使用函数 ctime 将秒数转化为字符串. 这个函数的返回类型是固定的:一个可能值为”Thu Dec 7 14:58:59 2000”。这个字符串的长度和显示格式是固定的。 清单 1,time 的使用 #include <time.h> int main () { time_t time_raw_format; time ( &time_raw_format ); //获取当前时间 printf (" time is [%d]n", time_raw_format); //用 ctime 将时间转换为字符串输出 printf ( "The current local time: %s", ctime(&time_raw_format)); return 0; } 自定义格式转换 为了更灵活的显示,需要把类型 time_t 转换为 tm 数据结构。tm 数据结构将时间分别保存到代表年,月,日,时,分,秒等不同的变量中。不再是一个令人费解的 64 位整数了。这种数据结构是各种自定义格式转换函数所需要的输入形式。 清单 2,数据结构 tm struct tm { int tm_sec; /* Seconds (0-60) */ int tm_min; /* Minutes (0-59) */ int tm_hour; /* Hours (0-23) */ int tm_mday; /* Day of the month (1-31) */ int tm_mon; /* Month (0-11) */ int tm_year; /* Year since 1900 */ int tm_wday; /* Day of the week (Sunday = 0)*/ int tm_yday; /* Day in the year (0-365; 1 Jan = 0)*/ int tm_isdst; /* Daylight saving time flag > 0: DST is in effect; = 0: DST is not effect; < 0: DST information not available */ }; 可以使用 gmtime() 和 localtime() 把 time_t 转换为 tm 数据格式,其中 gmtime() 把时间转换为格林威治时间;localtime 则转换为当地时间。 清单 3,时间转换函数定义 #include <time.h> struct tm *gmtime(const time_t *timep); struct tm *localtime(const time_t *timep); (编辑:应用网_丽江站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |