Linux编程基础之时间编程小结

        时间是编程过程中经常涉及到的,这部分知识其实不多,关键是把握住几个关键概念,使用起来就能思路清晰,得心应手了。这里只是我复习知识的笔记,高手请飘过~

第一个关键概念就是日历时间,它是指以某个标准时间点为基点到现在时刻的秒数,一般以1970.1.1零点为起点,这是最最基础的计量方式,有了这个基础数据,其它标准时间,本地时间便可轻松转化出来了.这个日历时间可通过系统调用time()来获取到。

第二个关键概念是世界标准时间,即格林威治标准时间,它可以通过系统调用gmtime()方法来由日历时间转换而来。

第三个关键概念是本地时间,即按当前所处时区来表示的本地时间,它也可以通过系统调用localtime()方法来由日历时间转换而来。

另外还有几个知识点要搞清,例如这个标准时间和本地时间的数据载体,即struct tm ,如何将时间转化成字符串等。

以上涉及的函数原型有:

①:time_t time(time_t *local)

②:struct tm *gmtime(const time_t *timep)

③:struct tm *localtime(const time_t *timep)

④:char * asctime(const struct tm *p)

⑤: char *ctime(const time_t *timep)

简单的知识图如下所示:

Linux编程基础之时间编程小结_第1张图片

代码文件:my_time.c

 1 #include <stdio.h>
2 #include <time.h>
3 #include <stdlib.h>
4
5 /***********************************************************
6 功能说明:Linux环境下时间相关的编程
7 author: [email protected]
8
9 ***********************************************************/
10
11 int main(int argc, char * argv[])
12 {
13
14 //获取日历时间
15 time_t cur = time(NULL);
16 printf("calendar time :%ld\n", cur);
17
18 //转化成标准时间
19 struct tm *pgmt = gmtime(&cur);
20
21 printf("GMT:%s\n", asctime(pgmt));
22
23 //转化成本地时间
24 struct tm *ploc = localtime(&cur);
25
26 printf("local time:%s\n", ctime(&cur));
27
28
29
30
31
32 }

运行结果如下:



你可能感兴趣的:(linux)