Linux下时间相关接口封装

本文详细介绍了Linux下与时间相关的系统调用,包括time、gmtime和localtime函数的使用,以及struct tm结构体成员的解释。同时,讨论了时间接口的封装,如获取当前本地和UTC时间的结构体及字符串表示,以及获取当前时区的方法。
摘要由CSDN通过智能技术生成

一、相关系统调用
1、time函数
函数原型:time_t time(time_t *time)
头文件:#include <time.h>
功能:获得系统当前时间
返回值(长整型):成功返回从公元1970-1-1,00:00:00到当前的秒数,失败返回-1
参数(传出参数):同返回值

2、gmtime函数
函数原型:struct tm *gmtime(const time_t *time)
头文件:#include <time.h>
功能:将从公元1970-1-1,00:00:00到当前的秒数时间转换成日常使用的年月日形式
返回值:日常生活中所使用的时间表示,用结构体struct tm表示,utc时间,不加时区
参数(传入参数):从公元1970-1-1,00:00:00到当前的秒数时间,长整型

3、localtime函数
函数原型:struct tm *localtime(const time_t time)
头文件:#include <time.h>
功能:将utc秒时间转换为年月日时分秒的形式,并加时区,表征当地时间
返回值:struct tm
,当地时间
参数(传入参数):从公元1970-1-1,00:00:00到当前的秒数时间,长整型

4、struct tm结构体成员
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日 */
int tm_isdst; // 夏令时标识符,夏令时tm_isdst为正;不实行夏令时tm_isdst为0
};

二、常用接口封装
1、获取当前本地时间,日常表示形式,使用结构体描述

int get_time_local_common(service_time_t *cur_time)
{
   
    time_t t;
    struct tm *tp;
    if((0 < time(&t)) && (NULL != (tp = localtime(&t))))
    {
   
        cur_time->year = tp->tm_year + 1900;
        cur_time->mouth = tp->tm_mon + 1;
        cur_time->week = tp->tm_wday;
        cur_time->day = tp->tm_mday;
        cur_time->hour = tp->tm_hour;
        cur_time->minute = tp->tm_min;
        cur_time->second = tp->tm_sec;
    }
    else
    {
   
        return -1;
    }
    return 0;
}

2、获取当前本地时间,日常表示形式,使用字符串描述

int get_time_local_string(char *time_str, size_t buf_len)
{
   
    time_t t
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值