C Program to find day of week given date

后端 未结 14 1397
梦谈多话
梦谈多话 2020-11-29 05:14

Is there a way to find out day of the week given date in just one line of C code?

For example

Given 19-05-2011(dd-mm-yyyy) gives me Thursday

14条回答
  •  半阙折子戏
    2020-11-29 05:37

    For Day of Week, years 2000 - 2099.

    uint8_t rtc_DayOfWeek(uint8_t year, uint8_t month, uint8_t day)
    {
        //static const uint8_t month_offset_table[] = {0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5}; // Typical table.
    
        // Added 1 to Jan, Feb. Subtracted 1 from each instead of adding 6 in calc below.
    
        static const uint8_t month_offset_table[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
    
        // Year is 0 - 99, representing years 2000 - 2099
    
        // Month starts at 0.
    
        // Day starts at 1.
    
        // Subtract 1 in calc for Jan, Feb, only in leap years.
        // Subtracting 1 from year has the effect of subtracting 2 in leap years, subtracting 1 otherwise.
        // Adding 1 for Jan, Feb in Month Table so calc ends up subtracting 1 for Jan, Feb, only in leap years.
        // All of this complication to avoid the check if it is a leap year.
        if (month < 2) {
            year--;
        }
    
        // Century constant is 6. Subtract 1 from Month Table, so difference is 7.
    
        // Sunday (0), Monday (1) ...
    
        return (day + month_offset_table[month] + year + (year >> 2)) % 7;
    
    } /* end rtc_DayOfWeek() */
    

提交回复
热议问题