APUE------时间和日期

来源:互联网 发布:java asm api 编辑:程序博客网 时间:2024/06/04 17:46

由UNIX内核提供的基本时间服务是计算自协调世界时(UTC)公元1970年1月1日00:00:00这一特定时间以来经过的秒数。

time函数返回当前时间和日期

#include <time.h>time_t time(time_t *calptr);//返回值:若成功,返回时间值;若出错,返回-1

如果参数非空;则时间值也存放在由calptr指向的单元内。

时钟通过clockid_t类型进行标识

标识符 选项 说明 CLOCK_REALTIME 实时系统时间 CLOCK_MONOTONIC _POSIX_MONOTONIC_CLOCK 不带负跳数的实时系统时间 CLOCK_PROCESS_CPUTIME_ID _POSIX_CPUTIME 调用进程的CPU时间 CLOCK_THREAD_CPUTIME_ID _POSIX_THREAD_CPUTIME 调用进程的CPU时间

clock_gettime函数可用于获取指定时钟的时间。

#include <sys/time.h>int clock_gettime(clockid_t clock_id, struct timespec *tsp);//返回值:若成功,返回0;若出错,返回-1
#include <sys/time.h>int clock_getres(clockid_t clock_id,struct timespec *tsp);//返回值:若成功,返回0;若出错,返回-1

clock_getres函数把参数tsp指向的timespec结构初始化为与clock_id参数对应的时钟精度。

要对特定的时钟设置时间,可以调用clock_settime函数

#include <sys/time.h>int clock_settime(clockid_t clock_id, const struct timespec *tsp)//返回值:若成功,返回0;若出错,返回-1

两个函数localtime和gmtime将日历时间转换成分解的时间,并将这些存放在一个tm结构中。

struct tm{    int tm_sec;    int tm_min;    int tm_hour;    int tm_mday;    int tm_mon;    int tm_year;    int tm_wday;    int tm_yday;    int tm_isdst;}
#include <time.h>struct tm *gmtime(const time_t *calptr);struct tm *localtime(const time_t *calptr);//两个函数的返回值:指向分解的tm结构的指针;若出错,返回NULL

localtime是将日历时间转换成本地时间。而gmtime则将日历时间转换成格林威治时间。

函数mktime将以本地时间的年、月、日等作为参数,将其变成time_t值

#include <time.h>time_t mktime(struct tm *tmptr);//返回值:若成功,返回日历时间;若出错,返回-1

函数strftime是一个类似于printf的时间值函数。

#include <time.h>size_t strftime(char *restrict buf, size_t maxsize,                 const char *restrict format,                const struct tm *restrict tmptr);size_t strftime_l(char *restrict buf, size_t maxsize,                  const char *restrict format,                  const struct tm *restrict tmptr,                   locale_t locale);//两个函数的返回值:若有空间,返回存入数组的字符数;否则,返回0

当然 strftime有一份自己的转换说明。自行百度

0 0
原创粉丝点击