C语言时间转换的参考示例

本文详细探讨了C语言中如何进行时间转换和处理,通过实例代码解析了时间戳与日期时间之间的转换,包括从系统时间获取、格式化输出等方面的知识。

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

 

#include <sys/time.h>

1、int gettimeofday(struct timeval*tv, struct timezone *tz);
其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果:
struct timezone{
int tz_minuteswest;/*格林威治时间往西方的时差*/
int tz_dsttime;/*DST 时间的修正方式*/
}
timezone 参数若不使用则传入NULL即可。
而结构体timeval的定义为:
struct timeval{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}
它获得的时间精确到微秒(1e-6 s)量级。
2、struct tm *localtime(const time_t *clock)和struct tm* localtime_r( const time_t* timer, struct tm* result )
多线程应用里面,应该用localtime_r函数替代localtime函数,因为localtime_r是线程安全的。

使用如下:
    struct timeval tv;
    gettimeofday(&tv, NULL);//获取1970-1-1到现在的时间结果保存到tv中
    uint64_t sec = tv.tv_sec;
    struct tm cur_tm;//保存转换后的时间结果
    localtime_r((time_t*)&sec, &cur_tm);
    char cur_time[24];
    snprintf(cur_time, 24, "%d-%02d-%02d %02d:%02d:%02d", cur_tm.tm_year+1900,
         cur_tm.tm_mon+1, cur_tm.tm_mday, cur_tm.tm_hour, cur_tm.tm_min, cur_
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值