**由于项目需要,需要写一个根据小时数转化为日期的算法,涉及到时间进位和闰年的2月天数
#include <stdio.h>
#include <stdbool.h>
char time[10] = {21, 1, 9, 17, 30}; //2021年1月9日17点30分
typedef struct time
{
/* data */
int hour;
int day;
int month;
int year;
} TimerTypedef;
TimerTypedef Timer;
void TimerInit()
{
Timer.year = time[0];
Timer.month = time[1];
Timer.day = time[2];
Timer.hour = time[3];
}
char isLeapYear(int year) //判断是否是闰年
{
year = year + 2000;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
{
return 1;
}
else
{
return 0;
}
}
void TimerHandler(char *timer, int hour)
{
TimerInit();
int hour_temp = 0;
int day_temp = 0;
int month_temp = 0;
int month_day[13] = {31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //注意这里把0号索引改成了跟12月一样的方便编程
Timer.hour += hour;
if (Timer.hour >= 24) //超过一个小时了
{
hour_temp = Timer.hour;
Timer.hour = hour_temp % 24; //时
Timer.day += hour_temp / 24; //天
while (Timer.day > month_day[Timer.month]) //大于当前月的天数
{
if (isLeapYear(Timer.year)) //闰年 29
{
month_day[2] = 29;
}
else month_day[2] = 28;
Timer.day = Timer.day - month_day[Timer.month];
Timer.month++;
if (Timer.month > 12)
{
month_temp = Timer.month;
Timer.month=1; //变为1月
Timer.year++; //年数累加
}
}
}
time[0] = Timer.year;
time[1] = Timer.month;
time[2] = Timer.day;
time[3] = Timer.hour;
}
int main(int argc, char const *argv[])
{
/* code */
for (int i = 0; i < 5; i++)
{
/* code */
printf("%d ", time[i]);
}
printf("\n");
TimerHandler(time, 119580);
for (int i = 0; i < 5; i++)
{
/* code */
printf("%d ", time[i]);
}
return 0;
}
例如 初始的时间字符串是 2021年1月9日17点30分 加上119580个小时,得到结果