您的位置:首页 > 运维架构 > Linux

linux下C时间编程(1)——时间显示与转换

2014-12-14 14:54 190 查看
时间显示:

本文将着重阐述在linux下C开发中实际应用的时间编程的一些方法和技巧,对一些原理性的东西并不进行深入的讨论,如果读者有更深刻的理解,欢迎加入讨论。

在实际C开发中,我们常常需要输出或者让程序显示当前系统时间,例如生成日记文件、游戏开发等等。回想一下,在命令行中我们使用date来实现这一功能,然而在程序中如何实现呢?相信有一些C基础的读者第一时间会想到time()函数。下面就让我来介绍一些比较常用的时间函数:

定义精度
time()
gettimeofday()微秒
clock_gettime()纳秒
这里还有一个老系统中经常使用的ftime()函数,精度为毫秒,由于在实际使用中已经被time()取代,所以在此不再列出。

这些函数都返回从 1970 年 1 月 1 日 0 点以来,到现在的时间,存储在相应的数据结构中。注:这里的时间都表示格林威治时间,也叫GMT或UTC时间。

例一:time()的使用

#include<stdio.h>
#include<time.h>//调用时间函数
int main()
{
	time_t time_now;
	time(&time_now);//获取当前时间,存入time_now的地址中
	printf("time:%ld\n",time_now);//注意数据类型应使用long int
	return 0;
}
运行结果:

gettimofday()和clock_gettime()函数由于不常使用,在此只给大家推荐一些举例。详见点击查看详细介绍

格式转换:

上例中的到的结果往往不是我们想要的,我们需要的是如2014年12月14日之类的有效时间显示,这就需要我们对得到的秒数进行格式转换。格式转换常常有两种方法。

1.固定格式转换:

固定格式转换使用ctime()函数就可以实现(char *ctime(const time_t *clock); ),这个函数的返回类型是固定的:一个可能值为Thu Dec 7 14:58:59 2000,这个字符串的长度是固定的,为26。实际开发中使用固定转换就够用了,而且很方便。

例二:固定转换

#include<stdio.h>
#include<time.h>
int main()
{
    time_t time_now;
	time(&time_now);//将地址传给time函数,获取当前时间
	printf("time is %ld\n",time_now);
	printf("current local time:%s",ctime(&time_now));//用ctime将时间转换为字符串输出
	return 0;
}
运行结果:

2.自定义格式转换:

用户可以根据自己的需要来设置转换的格式,实际应用中主要有两个函数:

struct tm *gmtime(const time_t *timep);//格林威治时间
struct tm *localtime(const time_t *timep);//当地时间
这两个函数将time_t格式转换为tm数据格式,数据结构tm如下:

struct tm
{
    int    tm_sec;        /* Seconds: 0-59 (K&R says 0-61?) */
    int    tm_min;        /* Minutes: 0-59 */
    int    tm_hour;    /* Hours since midnight: 0-23 */
    int    tm_mday;    /* Day of the month: 1-31 */
    int    tm_mon;        /* Months *since* january: 0-11 */
    int    tm_year;    /* Years since 1900 */
    int    tm_wday;    /* Days since Sunday (0-6) */
    int    tm_yday;    /* Days since Jan. 1: 0-365 */
    int    tm_isdst;    /* +1 Daylight Savings Time, 0 No DST,* -1 don't know */
};
转换完成后还需要调用asctime()和strftime()进行字符串输出。

asctime()与ctime()类似,格式固定,参见例二。

strftime()可与printf()函数类比,可以通过输入参数自定义时间的输出格式:

size_t strftime(char *outstr, size_t maxsize, const char *format,const struct tm *timeptr);


例三:自定义格式转换

#include<stdio.h>
#include<time.h>
int main()
{
	time_t time_now;
	struct tm * time_struct;
	char buf[100];
	time(&time_now);
	time_struct=localtime(&time_now);
	strftime(buf,100,"time is now:%I:%M%p.",time_struct);
	puts(buf);
	return 0;
}
运行结果:

这部分内容到这里就差不多了。这是我的第一篇blog,写的不好请多多包涵。本人还是以为在校学生,并没有过多的实际开发经验,有些地方的理解也许有偏差,也希望大家多多指正,帮助我更地理解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: