Unix提供的最基本的时间服务室日历时间(纪元时间),也就是计算1970年1月1日0时0分0秒到当前的秒数。该秒数用time_t表示。
typedef long     time_t;    /* 时间值time_t 为长整型的别名*/

1、获取/设置时间

1.1 time和time_t

函数time()可以用于获取当前日历时间
#include <time.h>
time_t time(time_t *calptr);
Returns: value of time if OK,−1 on error
      当前时间值(即1970年1月1日0时0分0秒到现在的秒数)保存给calptr指针指向的地址,也作为返回值。

1.2 指定时钟类型

Unix提供指定时钟类型来获取/设置时间的方法。
 #include <time.h>
int clock_getres(clockid_t clk_id, struct timespec *res);
int clock_gettime(clockid_t clk_id, struct timespec *tp);
int clock_settime(clockid_t clk_id, const struct timespec *tp);
Link with -lrt.编译时使用链接库lrt
clock_gettime()和clock_settime();函数提供了纳秒级别的时间,并且会根据clk_id的时间类型进行取值。
clock_getres 用于获取时间的分辨率。  clock_gettime()和clock_settime()使用的时间必须是时间分辨率的整数倍,不是整数倍也要切割成整数倍。
clockid_tclk_id用于指定计时时钟的类型,有以下选项:
CLOCK_REALTIME:系统实时时间,使用此选项时功能相当于time(),如果系统时间被用户修改过,则对应的时间相应改变
CLOCK_MONOTONIC:从系统启动这一刻起开始计时,不受系统时间被用户改变的影响
CLOCK_PROCESS_CPUTIME_ID:本进程运行的CPU时间
CLOCK_THREAD_CPUTIME_ID:本线程运行的CPU时间
 struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};

1.3 gettimeofday()与settimeofday()

Unix/Linux提供了微秒级别获取和设置时间的函数gettimeofday()与settimeofday(),但根据man手册的描述,这两个函数已经过时,此处不做介绍。仅列出原型(这两个函数编译需要glibc的支持)
       #include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv, const struct timezone *tz);

2、时间格式转换

    我们使用time()等函数获取的时间是一个time_t获取的从新纪元开始到当前所经过的秒数,是一个整数值。(calender time)
    我们很多情况下需要将其转换成我们可读的,向时分秒这样的时间(broken down time)。这就需要进行转化。
    时间转换图如 Figure6.9 所示


    我们使用struct tm来保存broken-down time
struct tm { /* a broken-down time */
int tm_sec; // 秒 【0~60】 60存在的原因是闰秒的存在
int tm_min; //分
int tm_hour; //时
int tm_mday; //日
int tm_mon; //月
int tm_year; //年 结构中记录的是从1900至今的年数
int tm_wday; //星期几 【0~6】
int tm_yday; // 一年中第几天
int tm_isdst; // 夏时制标志
};

夏时制,夏时令(Daylight Saving Time:DST),又称“日光节约时制”和“夏令时间”,是一种为节约能源而人为规定地方时间的制度,在这一制度实行期间所采用的统一时间称为“夏令时间”。一般在天亮早的夏季人为将时间提前一小时,可以使人早起早睡,减少照明量,以充分利用光照资源,从而节约照明用电。
    Unix提供了时间格式转换的函数:

2.1 time_t与struct tm相互转化


time_t转化成struct tm
#include <time.h>
struct tm *gmtime(const time_t *calptr);
struct tm *localtime(const time_t *calptr);
Both return: pointer to broken-down time,NULLon error
gmtime 转换成国际标准时间
localtime转换成本地时间(考虑到本地时区和夏时制标志)
struct tm转化成time_t
#include <time.h>
time_t mktime(struct tm *tmptr);
Returns: calendar time if OK,−1 on error
example:
#include<stdio.h>
#include <time.h>
#include<sys/time.h>
int main(void)
{
time_t calptr;
if (time(&calptr) == -1)
{
printf("Error: time() failed!\n");
exit(0);
}
printf("Time(time_t) now is: %d\n",(long) calptr);
/*
* 转换成可读到时间
*/
struct tm *gmptr; //国际标准时间
struct tm *localptr; //本地时间 /* 转换成国际标准时间 */
printf("\n\n ----------gm time--------------\n");
if (NULL == (gmptr = gmtime(&calptr)))
{
printf("Error: can't convert time_t to struct tm by gmtime()!\n");
exit(0);
}
printf("year:%d,\tMonth:%d,\tDay:%d,\tWeek:%d\n", gmptr->tm_year, gmptr->tm_mon, gmptr->tm_mday, gmptr->tm_wday);
printf("Hour:%d,\tMin:%d,\t,sec:%d\n", gmptr->tm_hour, gmptr->tm_min, gmptr->tm_sec);
/* 转换成本地标准时间 */
printf("\n\n ----------local time--------------\n");
if (NULL == (localptr = localtime(&calptr)))
{
printf("Error: can't convert time_t to struct tm by localtime()!\n");
exit(0);
}
printf("year:%d,\tMonth:%d,\tDay:%d,\tWeek:%d\n", localptr->tm_year, localptr->tm_mon, localptr->tm_mday, localptr->tm_wday);
printf("Hour:%d,\tMin:%d,\t,sec:%d\n", localptr->tm_hour, localptr->tm_min, localptr->tm_sec);
return 0;
}

运行结果:
windeal@ubuntu:~/Windeal/apue$ ./exe
Time(time_t) now is: 1409207607
----------gm time--------------
year:114, Month:7, Day:28, Week:4
Hour:6, Min:33, ,sec:27
----------local time--------------
year:114, Month:7, Day:28, Week:4
Hour:14, Min:33, ,sec:27

东八区,快了8个小时

2.2 转换成格式化字符串

#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);
——Both return: number of characters stored in array if room, 0 otherwise

Example:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int
main(void)
{
time_t t;
struct tm *tmp;
char buf1[16];
char buf2[64];
time(&t);
tmp = localtime(&t);
if (strftime(buf1, 16, "time and date: %r, %a %b %d, %Y", tmp) == 0)
printf("buffer length 16 is too small\n");
else
printf("%s\n", buf1); if (strftime(buf2, 64, "time and date: %r, %a %b %d, %Y", tmp) == 0)
printf("buffer length 64 is too small\n");
else
printf("%s\n", buf2);
exit(0);
}

运行结果:
windeal@ubuntu:~/Windeal/apue$ ./exe
buffer length 16 is too small
time and date: 02:43:55 PM, Thu Aug 28, 2014

字符串转换成struct tm格式
#include <time.h>
char *strptime(const char *restrictbuf,const char *restrictformat,struct tm *restricttmptr);
Returns: pointer to one character past last character parsed,NULLotherwise

关于转换符号:










APUE学习笔记——6.10 时间与时间例程 time_t的更多相关文章

  1. APUE学习笔记——3.10文件共享

    基本概念 内核使用3个数据结构描述一个打开的文件:进程表.文件表.V节点表 首先了解3种数据结构的概念     1 进程表         每一个进程有一个进程表.进程表里是一组打开的文件描述符,如标 ...

  2. APUE学习笔记——10.9 信号发送函数kill、 raise、alarm、pause

    转载注明出处:Windeal学习笔记 kil和raise kill()用来向进程或进程组发送信号 raise()用来向自身进程发送信号. #include <signal.h> int k ...

  3. MYSQL学习笔记三:日期和时间函数

    MYSQL学习笔记三:日期和时间函数 1. 获取当前日期的函数和获取当前时间的函数 /*获取当前日期的函数和获取当前时间的函数.将日期以'YYYY-MM-DD'或者'YYYYMMDD'格式返回 */ ...

  4. 【python学习笔记】10.充电时刻

    [python学习笔记]10.充电时刻 任何python都可以作为模块倒入 *.pyc:平台无关的经过编译的的python文件, 模块在第一次导入到程序中时被执行,包括定义类,函数,变量,执行语句 可 ...

  5. APUE学习笔记3_文件IO

    APUE学习笔记3_文件IO Unix中的文件IO函数主要包括以下几个:open().read().write().lseek().close()等.这类I/O函数也被称为不带缓冲的I/O,标准I/O ...

  6. Java程序猿的JavaScript学习笔记(10—— jQuery-在“类”层面扩展)

    计划按例如以下顺序完毕这篇笔记: Java程序猿的JavaScript学习笔记(1--理念) Java程序猿的JavaScript学习笔记(2--属性复制和继承) Java程序猿的JavaScript ...

  7. Linux学习笔记(10)linux网络管理与配置之一——主机名与IP地址,DNS解析与本地hosts解析(1-4)

    Linux学习笔记(10)linux网络管理与配置之一——主机名与IP地址,DNS解析与本地hosts解析 大纲目录 0.常用linux基础网络命令 1.配置主机名 2.配置网卡信息与IP地址 3.配 ...

  8. SpringBoot学习笔记(10):使用MongoDB来访问数据

    SpringBoot学习笔记(10):使用MongoDB来访问数据 快速开始 本指南将引导您完成使用Spring Data MongoDB构建应用程序的过程,该应用程序将数据存储在MongoDB(基于 ...

  9. Flutter学习笔记(10)--容器组件、图片组件

    如需转载,请注明出处:Flutter学习笔记(10)--容器组件.图片组件 上一篇Flutter学习笔记(9)--组件Widget我们说到了在Flutter中一个非常重要的理念"一切皆为组件 ...

随机推荐

  1. C++在VS下创建、调用dll

    转自:http://www.cnblogs.com/houkai/archive/2013/06/05/3119513.html 目录 1.dll的优点 代码复用是提高软件开发效率的重要途径.一般而言 ...

  2. 2017年4月16日 一周AnswerOpenCV佳作赏析

    2017年4月16日 一周AnswerOpenCV佳作赏析 1.HelloHow to smooth edge of text in binary image, based on threshold. ...

  3. 20145328 《Java程序设计》第8周学习总结

    20145328 <Java程序设计>第8周学习总结 教材学习内容总结 第十四章 NIO与NIO2 NIO使用频道(channel)来衔接数据节点,对数据区的标记提供了clear(),re ...

  4. strcpy、sprintf、memcpy的区别

    char*strcpy(char *dest, const char *src); 其对字符串进行操作,完成从源字符串到目的字符串的拷贝,当源字符串的大小大于目的字符串的最大存储空间后,执行该操作会出 ...

  5. Linux下ping命令参数详细解析

    -a Audible ping. #Audible ping. -A Adaptive ping. Interpacket interval adapts to round-trip time, so ...

  6. Mac下需要安装的一些软件及常用的配置文件

    常用软件配置文件 1..gitconfig # This is Git's per-user configuration file. [user] name = 张文 email = zhangwen ...

  7. [BZOJ2688]折线统计

    Description 二维平面上有n个点(xi, yi),现在这些点中取若干点构成一个集合S,对它们按照x坐标排序,顺次连接,将会构成一些连续上升.下降的折线,设其数量为f(S).如下图中,1-&g ...

  8. Linux 修改SSH端口及禁用ROOT远程SSH登陆

    打开配置文件: vim /etc/ssh/sshd_config 修改Port及PermitRootLogin节点 : //默认为yes 允许 no表示禁止 PermitRootLogin no // ...

  9. 第十一篇:Spark SQL 源码分析之 External DataSource外部数据源

    上周Spark1.2刚发布,周末在家没事,把这个特性给了解一下,顺便分析下源码,看一看这个特性是如何设计及实现的. /** Spark SQL源码分析系列文章*/ (Ps: External Data ...

  10. jQuery实际案例①——淘宝精品广告(鼠标触碰切换图片、自动轮播图片)

    遇到的问题:自动轮播的实现,实质与轮播图一样儿一样儿的,不要被不同的外表所欺骗,具体的js代码如下: