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. Redis学习笔记之Redis中5种数据结构的使用场景介绍

    原来看过 redisbook 这本书,对 redis 的基本功能都已经熟悉了,从上周开始看 redis 的源码.目前目标是吃透 redis 的数据结构.我们都知道,在 redis 中一共有5种数据结构 ...

  2. centos7安装kvm环境采用网桥模式并创建虚拟机制作openstack需要的镜像

    初始环境的安装:centos7 mini iso镜像进行安装的系统 采用的环境是vm该软件,联网方式NAT模式下配置的静态ip(如何在NAT模式下配置静态ip参考之前的文章) 1.由于要安装kvm环境 ...

  3. 20145302张薇《Java程序设计》实验二报告

    20145302张薇<Java程序设计>实验二:Java面向对象程序设计 使用TDD的方式设计实现复数类:Complex 测试代码 import org.junit.Test; publi ...

  4. Python学习笔记(十二)—Python3中pip包管理工具的安装【转】

    本文转载自:https://blog.csdn.net/sinat_14849739/article/details/79101529 版权声明:本文为博主原创文章,未经博主允许不得转载. https ...

  5. Continue SQL query even on errors

    trymysql --force < sample_data.sql Mysql help section says -f, --force         Continue even if w ...

  6. ImportError: No module named argparse

    如果有root权限,可以运行: easy_install argparse 如果没有root权限,As a simple solution copy argparse.py from https:// ...

  7. 【转】Python 字符串大小写转换

    转载自:python 中字符串大小写转换 一.pyhton字符串的大小写转换, 常用的有以下几种方法: 1.对字符串中所有字符(仅对字母有效)的大小写转换,有两个方法: print 'just to ...

  8. 深入理解Java枚举类型(enum)

    https://blog.csdn.net/javazejian/article/details/71333103 深入理解Java类型信息(Class对象)与反射机制 深入理解Java枚举类型(en ...

  9. 在activity之间传递数据

    在activity之间传递数据 一.简介 二.通过intent传递数据 1.在需要传数据的界面调用 intent.putExtra("data1", "我是fry&quo ...

  10. shell数组中“和@的妙用

    #!/bin/bashlist=(4k"8k a bit""16k abc""32k gold"64k)for i in "${l ...