时间处理函数

本文详细介绍了时间处理函数及其用法,包括structtm、structtimespec、structtimeval、time、clock_gettime、gettimeofday等核心函数,并对比了它们在时间处理方面的差异与应用场景。同时,阐述了如何通过localtime和gmtime函数实现日期与时间的转换,以及如何使用mktime和strftime进行日期格式化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

时间处理函数

struct tm {
               int tm_sec;         /* seconds */
               int tm_min;         /* minutes */
               int tm_hour;        /* hours */
               int tm_mday;        /* day of the month */
               int tm_mon;         /* month */
               int tm_year;        /* year */
               int tm_wday;        /* day of the week */
               int tm_yday;        /* day in the year */
               int tm_isdst;       /* daylight saving time */
           };

struct timespec {
               time_t   tv_sec;        /* seconds */
               long     tv_nsec;       /* nanoseconds */
           };


struct timeval {
               time_t      tv_sec;     /* seconds */
               suseconds_t tv_usec;    /* microseconds */
           };

time函数返回当前时间
#include<time.h>
time_t time(time_t *calptr);
成功-- 时间值(秒数),出错-- -1
若参数calptr非空,时间值也存在calptr上


clock_gettime函数
#include<sys/time.h>
int  clock_gettime(clockid_t clock_id,struct timespec *tsp);
成功-- 0,出错-- -1
clock_id  参数设置为CLOCK_REALTIME时,功能和time函数差不多,但是时间的精度更高。



gettimeofday函数
#include<sys/time.h>
int  gettimeofday(struct timeval *restrict tp,void *restrict tzp);
总是返回-- 0
tzp 参数一定为--NULL


localtime函数 和 gmtime函数
#include<time.h>
struct tm *gmtime(const time_t *calptr);
struct tm *localtime(const time_t *calptr);
成功--tm结构体的指针,出错-- NULL

localtime函数:将日历时间转换为本地时间
gmtime函数:将日历时间转换为统一时间的年、月、日、时、分、秒、周日分解结构。


mktime函数
#include<time.h>
time_t mktime(struct tm *tmptr);
成功-- 日历时间,出错-- -1


函数strftime
#include<time.h>
size_t strftime(char *buf,size_t maxsize,const char *format,const struct tm *tmptr);
若是buf空间够装下要转换的内容,则返回存入数组buf的字符数,否则-- 0
buf     参数--存储时间
maxsize 参数--数组的大小
format  参数--格式:%c--时间和日期,%a--缩写的星期,%r--本地时间(12小时制度),要更多格式查表即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值