一、相关系统调用
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