C实现时间戳加减秒数

struct datetime {
	unsigned short year;	/* 年 */
	unsigned char mon;		/* 月(1 ~ 12) */
	unsigned char day;		/* 日(1 ~ 31) */
	unsigned char hour;		/* 时(0 ~ 23) */
	unsigned char min;		/* 分(0 ~ 59) */
	unsigned char sec;		/* 秒(0 ~ 59) */
};
static int datetime_subjion_sec(struct datetime *ldt, int sec)	
{
	int tmp_sec = ldt->sec;
	int tmp_min = ldt->min;
	int tmp_hour = ldt->hour;
	int tmp_day = ldt->day;
	int tmp_month = ldt->mon;
	int tmp_year = ldt->year;

	if (NULL == ldt) {
		return -1;
	}

	tmp_sec += sec;
	if (tmp_sec >= 0 && tmp_sec < 60) {
		ldt->sec = tmp_sec;
		return 0;
	}

	tmp_min += tmp_sec / 60;
	tmp_sec %= 60;
	if (tmp_sec < 0) {
		tmp_min--;
		tmp_sec += 60;
	}

	if (tmp_min >= 0 && tmp_min < 60) {
		ldt->sec = tmp_sec;
		ldt->min = tmp_min;
		return 0;
	}
	
	tmp_hour += tmp_min / 60;
	tmp_min %= 60;
	if (tmp_min < 0) {
		tmp_hour--;
		tmp_min += 60;
	}

	if (tmp_hour >= 0 && tmp_hour < 24) {
		ldt->sec = tmp_sec;
		ldt->min = tmp_min;	
		ldt->hour = tmp_hour;
		return 0;
	}

	tmp_day += tmp_hour / 24;
	tmp_hour %= 24;
	if (tmp_hour < 0) {
		tmp_day--;
		tmp_hour += 24;
	}

	while (tmp_day > noDays(tmp_month, tmp_year)) {
		tmp_day -= noDays(tmp_month, tmp_year);
		tmp_month++;
		if (tmp_month >= 12) {
			tmp_month -= 12;
			tmp_year++;
		}
	}

	while (tmp_day < 0) {
			tmp_month--;
			if (tmp_month < 0) {
					tmp_month += 12;
					tmp_year--;
			}
			tmp_day += noDays(tmp_month, tmp_year);
	}	

	ldt->sec = tmp_sec;
	ldt->min = tmp_min;
	ldt->hour = tmp_hour;
	ldt->day = tmp_day;
	ldt->mon = tmp_month;
	ldt->year =tmp_year;

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值