C Program to find day of week given date

后端 未结 14 1282
梦谈多话
梦谈多话 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:19

    The answer I came up with:

    const int16_t TM_MON_DAYS_ACCU[12] = {
        0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
    };
    
    int tm_is_leap_year(unsigned year) {
        return ((year & 3) == 0) && ((year % 400 == 0) || (year % 100 != 0));
    }
    
    // The "Doomsday" the the day of the week of March 0th,
    // i.e the last day of February.
    // In common years January 3rd has the same day of the week,
    // and on leap years it's January 4th.
    int tm_doomsday(int year) {
        int result;
        result  = TM_WDAY_TUE;
        result += year;       // I optimized the calculation a bit:
        result += year >>= 2; // result += year / 4
        result -= year /= 25; // result += year / 100
        result += year >>= 2; // result += year / 400
        return result;
    }
    
    void tm_get_wyday(int year, int mon, int mday, int *wday, int *yday) {
        int is_leap_year = tm_is_leap_year(year);
        // How many days passed since Jan 1st?
        *yday = TM_MON_DAYS_ACCU[mon] + mday + (mon <= TM_MON_FEB ? 0 : is_leap_year) - 1;
        // Which day of the week was Jan 1st of the given year?
        int jan1 = tm_doomsday(year) - 2 - is_leap_year;
        // Now just add these two values.
        *wday = (jan1 + *yday) % 7;
    }
    

    with these defines (matching struct tm of time.h):

    #define TM_WDAY_SUN 0
    #define TM_WDAY_MON 1
    #define TM_WDAY_TUE 2
    #define TM_WDAY_WED 3
    #define TM_WDAY_THU 4
    #define TM_WDAY_FRI 5
    #define TM_WDAY_SAT 6
    
    #define TM_MON_JAN  0
    #define TM_MON_FEB  1
    #define TM_MON_MAR  2
    #define TM_MON_APR  3
    #define TM_MON_MAY  4
    #define TM_MON_JUN  5
    #define TM_MON_JUL  6
    #define TM_MON_AUG  7
    #define TM_MON_SEP  8
    #define TM_MON_OCT  9
    #define TM_MON_NOV 10
    #define TM_MON_DEC 11
    

提交回复
热议问题