C语言小时到日期转换算法

**由于项目需要,需要写一个根据小时数转化为日期的算法,涉及到时间进位和闰年的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个小时,得到结果
在这里插入图片描述

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值