C Program to find day of week given date

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

    As reported also by Wikipedia, in 1990 Michael Keith and Tom Craver published an expression to minimise the number of keystrokes needed to enter a self-contained function for converting a Gregorian date into a numerical day of the week.

    The expression does preserve neither y nor d, and returns a zero-based index representing the day, starting with Sunday, i.e. if the day is Monday the expression returns 1.

    A code example which uses the expression follows:

    int d    = 15   ; //Day     1-31
    int m    = 5    ; //Month   1-12`
    int y    = 2013 ; //Year    2013` 
    
    int weekday  = (d += m < 3 ? y-- : y - 2, 23*m/9 + d + 4 + y/4- y/100 + y/400)%7;  
    

    The expression uses the comma operator, as discussed in this answer.

    Enjoy! ;-)

提交回复
热议问题