美文网首页
C语言应用(2)——判断当前时间是否在一个时间段内(含跨天)

C语言应用(2)——判断当前时间是否在一个时间段内(含跨天)

作者: Leung_ManWah | 来源:发表于2022-02-22 17:41 被阅读0次

    一、需求

    举例有如下几个时间段:

    A.0-7点
    B.7-20点
    C.21-7点

    A、B两个时间段判定很简单,只需获取当前时间点对应的小时值,例如当前时间为14点,那么得到小时值为14,然后根据 当前时间 ≥ 开始时间,同时当前时间 < 结束时间,判断是否处在某个时间段内。

    但将区间值换成C组配置,那么以上的方法就不再适用。我们来观察下C组的配置,起始时间为21点,结束时间为7点,很明显已经跨天了。
    当前时间为0-6点时,以上方法不再适用,所以要增加判断是否 结束时间 < 开始时间

    二、代码

    #include <stdio.h>
    #include <stdint.h>
    #include <stdbool.h>
    #include "time.h"
    
    static uint8_t startHour = 21;
    static uint8_t endHour = 7;
    
    static bool isInTime(uint8_t now)
    {
        // 过夜
        if(endHour < startHour) 
        {  
            if(now >= endHour && now < startHour) 
            {  
                return false;  
            } 
            else 
            {  
                return true;  
            }  
        }   
        // 当天
        else 
        {  
            if(now >= startHour && now < endHour) 
            {  
                return true;  
            } 
            else 
            {  
                return false;  
            }  
        }   
    }
    
    int main()
    {
        char str[100];
        struct tm *time;
        uint16_t year, yday;
        uint8_t month, day, week, hour, minute, second;
        time_t timestamp = 1645444800;  /*北京时间2022-02-21 20:00:00*/
    /*
        几个用于测试的时间戳和北京时间对应
        1645444800 = 2022-02-21 20:00:00(北京时间) 
        1645448400 = 2022-02-21 21:00:00
        1645455600 = 2022-02-21 23:00:00
        1645459200 = 2020-02-22 00:00:00
        1645484400 = 2020-02-22 07:00:00
        1645488000 = 2020-02-22 08:00:00
    */    
    
        /* 北京时间补偿 */
        timestamp += 8*60*60;
        /* 调用系统函数 */
        time = localtime(&timestamp);
        
        year = time->tm_year;   /* 自1900年算起 */
        month = time->tm_mon;   /* 从1月算起,范围0-11 */
        week = time->tm_wday;   /* 从周末算起,范围0-6 */
        yday = time->tm_yday;  /* 从1月1日算起,范围0-365 */
        day = time->tm_mday;    /* 日: 1-31 */
        hour = time->tm_hour;   /* 小时:0-23点,UTC+0时间 */
        minute = time->tm_min;  /* 分钟:0-59 */
        second = time->tm_sec;  /* 0-60,偶尔出现的闰秒 */
        
        /* 时间校正 */
        year += 1900;
        month += 1;
        week += 1;
        
        printf("UNIX时间戳:%d\r\n", timestamp);
        printf("开始时间:%d点\r\n结束时间:%d点\r\n", startHour, endHour);
        
        /* 格式化时间字符串 */
        strftime(str, 100, "%F %T", time);  /* 2020-07-01 02:16:51 */
        printf("%s\r\n", str);
        
        if(isInTime(hour))
        {
            printf("在时间段内\r\n", str);
        }
        else
        {
            printf("不在时间段内!!!\r\n", str);
        }
       
       return 0;
    }
    

    测试结果:



    • 由 Leung 写于 2022 年 2 月 22 日

    • 参考:Java判断某时间是否在一个时间段
        判定某个小时是否处于一个时间区间的实现(含跨天)

    相关文章

      网友评论

          本文标题:C语言应用(2)——判断当前时间是否在一个时间段内(含跨天)

          本文链接:https://www.haomeiwen.com/subject/ynpglrtx.html