linux时间函数的坑

今天遇到一个需求,用户输入一个时间结构体,函数返回这个时间的上一秒的时间结构体,自己实现时发现要判断的逻辑太复杂,很容易出问题,于是在linux时间函数上学习了一下找到一种办法解决

1.利用mktime函数把用户自定义时间转换成秒数   time_t mktime(struct tm *tm);

2.秒数减一,利用localtime_r函数转换成时间    struct tm *localtime_r(const time_t *timep, struct tm *result);

time_t实际上就是 long long int ,tm结构体定义如下

           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 */
           };

注意的是,mktime传入的结构体中tm_year= usrYear - 1900, tm_mon = usrMonth - 1;,否则nktime返回-1

而localtime解析出来后,得到的结构体的tm_year和tm_mon也要一样转化一下才能得到正确的时间

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>

int main()
{
	struct tm t1 = { 0 };
	struct tm t2 = { 0 };
	t1.tm_year = 2019 - 1900; t1.tm_mon = 5 - 1; t1.tm_mday = 27; t1.tm_hour = 16; t1.tm_min = 22 ; t1.tm_sec = 30;
	time_t seconds = mktime( &t1 );
	printf("seconds = %lld\n" , seconds);
	seconds = seconds - 1;
	localtime_r( &seconds , &t2 );
	printf("%d-%d-%d %d:%d:%d\n" , t2.tm_year + 1900 , t2.tm_mon + 1 , t2.tm_mday , t2.tm_hour , t2.tm_min , t2.tm_sec );
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值