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;
}
C实现时间戳加减秒数
最新推荐文章于 2023-04-19 18:45:04 发布