Linux 时间编程

来源:互联网 发布:中央电大网络教育绵阳 编辑:程序博客网 时间:2024/06/02 06:22

相关概念:
Coordinated Universal Time(UTC):世界标准时间,也就是大家所熟知的格林威治标准时间(Greenwich Mean Time,GMT)。

Calendar Time:日历时间,是用“从一个标准时间点(如:1970年1月1日0点)到此时 经过的秒数 ”来表示的时间。

获取日历时间

函数原形:
time_t time(time_t *t);

函数功能:
返回当前日历时间,距离格林尼治时间1970年1月1日0时0分0秒(Epoch)有多少秒。

所属头文件:

#include <time.h>

返回值:
成功,返回距离Epoch有多少秒;失败,返回-1.

参数说明:
指针t:如果t不是空指针,则返回的时间会保存在t指向的位置。

获取格林威治时间

函数原形:
struct tm *gmtime(const time_t *timep);
这里写图片描述
函数功能:
将timep指定的日历时间转化为世界标准时间(格林尼治时间)。

所属头文件:

#include <time.h>

返回值:
成功,返回世界标准时间,以结构体struct tm的形式来存储;失败,返回null。

参数说明:
timep:待转化的日历时间的指针。

获取本地时间

函数原形:
struct tm *localtime(const time_t *timep);

函数功能:
将timep指定的日历时间转化为当地的时间。

所属头文件:

#include <time.h>

返回值:
成功,返回当地时间,以结构体struct tm的形式来存储;
失败,返回null。struc tm结构体参看上面

参数说明:
timep:待转化的日历时间的指针。

以字符串方式显示时间

函数原形:
char *asctime(const struct tm *tmk);

函数功能:
将tm struct形式的时间转化为字符串形式的时间。

所属头文件:

#include <time.h>

返回值:
以特定的字符串方式显示的时间。

参数说明:
tmk:待转化的struct tm格式的时间。

获取高精度时间

函数原形:
int gettimeofday(struct timeval *tv, struct timezone *tz);

函数功能:
获取从Epoch开始计时的秒数和微秒数。时间函数可以用于计算其他函数运行所需要的时间长度。

所属头文件:

#include <sys/time.h>

返回值:
获取成功返回0,获取失败返回-1.

参数说明:
timeval *tv:记录的是从Epoch开始的秒数和微秒数,结构如下图所示:注意,此处的微秒加上秒是距离Epoch的时间。
这里写图片描述
timezone *tz:在linux中不使用,通常为NULL。结构如下图所示:
这里写图片描述

例程:

/* 本文件是关于时间编程的代码 */#include <time.h>#include <stdio.h>#include <sys/time.h>void main(){    time_t ctime;    struct tm *tm_gw;    struct tm *tm_local;    char *asc_tm;    struct timeval tv;    int result_micsecond;    //获取当前的日历时间    ctime = time(NULL);    printf("Calendar time is %d.\n", ctime);    //获取当前的格林威治时间,即世界标准时间    tm_gw = gmtime(& ctime);    printf("the UTC is: %d/%d/%d,%d:%d:%d\n",        tm_gw->tm_year + 1900, tm_gw->tm_mon + 1, tm_gw->tm_mday,         tm_gw->tm_hour, tm_gw->tm_min, tm_gw->tm_sec);    //获取当前的当地时间    tm_local = localtime(& ctime);    printf("the local time is: %d/%d/%d,%d:%d:%d\n",        tm_local->tm_year + 1900, tm_local->tm_mon + 1, tm_local->tm_mday,         tm_local->tm_hour, tm_local->tm_min, tm_local->tm_sec);    //获取字符串形式的时间    asc_tm = asctime(tm_local);    printf("the string of time is %s", asc_tm);    //获取高精度时间    result_micsecond = gettimeofday(&tv, NULL);    if (result_micsecond == 0)        printf("microsecond is %d.\n", tv.tv_usec);}
0 0