linux时间编程

来源:互联网 发布:十大网络官场小说 编辑:程序博客网 时间:2024/06/05 06:14

相关函数

时间获取

#include <sys/time.h>
int gettimeofday(struct timeval*tv, struct timezone *tz); //获取日历时间,包括秒、微妙、时区信息,较time()更详细。

#include <time.h>
time_t time(time_t *timer);  //获取日历时间(从1970.1.1:0:0:0开始的秒数).

时间转换

#include<time.h>

struct tm *gmtime(const time_t *time);  //将日历时间转换为格林威治时间.

struct tm *localtime(const time_t *clock);   //将日历时间转换为本地时间,格林威治时间形式.
char *ctime(const time_t *time);    //将日历时间直接转换为格林威治时间的字符串形式.
char* asctime (const struct tm * timeptr).;   //将格林威治时间转换为字符串形式.

数据结构

time_t = long类型。

struct timeval 
{

long tv_sec;// seconds

long tv_usec; // and microseconds

};
struct timezone
{

int tz_minuteswest;//格林威治时间往西方的时差

int tz_dsttime;//DST 时间的修正方式

};

struct tm 
{

int tm_sec;      /* 秒 – 取值区间为[0,59] */

int tm_min;      /* 分 - 取值区间为[0,59] */

int tm_hour;      /* 时 - 取值区间为[0,23] */

int tm_mday;      /* 一个月中的日期 - 取值区间为[1,31] */

int tm_mon;      /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */

int tm_year;      /* 年份,其值等于实际年份减去1900 */

int tm_wday;      /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */

int tm_yday;      /* 从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日

 };
 

测试代码

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>

int main(int argc, char **argv)
{

time_t calendar_time;

struct tm *utc_time = NULL;

struct timeval tval;

struct timezone tzone;


calendar_time = time(NULL); //time(&time_1); 获取日历时间

printf("[%s:%d] time calendar_time:%ld\n\n", __func__, __LINE__, calendar_time);


printf("[%s:%d] ctime UTC:%s\n", __func__, __LINE__, ctime(&calendar_time)); //将日历时间转换为格林威治时间的字符串形式.


utc_time = gmtime(&calendar_time); //将日历时间转换为格林威治时间.


printf("[%s:%d] asctime UTC:%s\n", __func__, __LINE__, asctime(utc_time)); //将格林威治时间转换为字符串形式.


utc_time = localtime(&calendar_time); //将日历时间转换为本地时间.


printf("[%s:%d] localtime:%s\n", __func__, __LINE__, asctime(utc_time)); //将本地时间转换为字符串形式.


gettimeofday(&tval, &tzone); //该函数与time() 很像爱那个,但是可以精确到us, 同时可以获取时区信息(很少使用).

printf("[%s:%d] gettimeofday tval.tv_sec:%d, tval.tv_sec:%d, tzone:%d\n", __func__, __LINE__, tval.tv_sec, tval.tv_usec, tzone.tz_minuteswest);


sleep(2); //休眠挂起2秒.

usleep(2); //休眠挂起2微秒.


return 0;

}


运行结果

[root@localhost test]# ./time
[main:14] time calendar_time:1432222746

[main:16] ctime UTC:Thu May 21 23:39:06 2015

[main:20] asctime UTC:Thu May 21 15:39:06 2015

[main:24] localtime:Thu May 21 23:39:06 2015

[main:27] gettimeofday tval.tv_sec:1432222746, tval.tv_sec:222842, tzone:-480

0 0
原创粉丝点击