浅析Linux中的时间编程和实现原理(一) Linux应用层的时间编程
使用 tm 来表示时间,您就可以调用 asctime() 和 strftime() 将时间转换为字符串了。asctime() 的输出格式固定,和 ctime() 相同。strftime() 则类似我们最熟悉的 printf() 函数,您可以通过输入参数自定义时间的输出格式。 size_t strftime(char *outstr, size_t maxsize, const char *format, const struct tm *timeptr); 清单 4,时间显示转换 int main () { time_t time_raw_format; struct tm * time_struct; char buf [100]; time ( &time_raw_format ); time_struct = localtime ( &time_raw_format ); strftime (buf,100,"It is now: %I:%M%p.",time_struct); puts (buf); return 0; } 该例子程序的输出结果如下: It is now: 02:45PM. 从以上的例子可以看到,利用从 time() 得到的时间值,可以调用各种转换函数将其转换成更方便人们阅读的形式。 此外从前面的总结中我们也了解到,还有两个 C 函数可以获得当前时间,gettimeofday() 以及 clock_gettime(),它们分别返回 struct timeval 或者 timespec 代表的高精度的时间值。在目前的 GLibC 中,还没有直接把 struct timeval/timespec 转换为 struct tm 的函数。一般的做法是将 timeval 中的 tv_sec 转换为 tm,使用上面所述的方法转换为字符串,最后在显示的时候追加上 tv_usec,比如下面的例子代码: 清单 5,更多时间显示转换 struct timeval tv; time_t nowtime; struct tm *nowtm; char tmbuf[64], buf[64]; gettimeofday(&tv, NULL); //获取当前时间到 tv nowtime = tv.tv_sec; //nowtime 存储了秒级的时间值 nowtm = localtime(&nowtime); //转换为 tm 数据结构 //用 strftime 函数将 tv 转换为字符串,但 strftime 函数只能达到秒级精度 strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S", nowtm); //将毫秒值追加到 strftime 转换的字符串末尾 snprintf(buf, sizeof buf, "%s.%06d", tmbuf, tv.tv_usec); (编辑:应用网_丽江站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |