C Program to find day of week given date

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

    Here's a C99 version based on wikipedia's article about Julian Day

    #include 
    
    const char *wd(int year, int month, int day) {
      /* using C99 compound literals in a single line: notice the splicing */
      return ((const char *[])                                         \
              {"Monday", "Tuesday", "Wednesday",                       \
               "Thursday", "Friday", "Saturday", "Sunday"})[           \
          (                                                            \
              day                                                      \
            + ((153 * (month + 12 * ((14 - month) / 12) - 3) + 2) / 5) \
            + (365 * (year + 4800 - ((14 - month) / 12)))              \
            + ((year + 4800 - ((14 - month) / 12)) / 4)                \
            - ((year + 4800 - ((14 - month) / 12)) / 100)              \
            + ((year + 4800 - ((14 - month) / 12)) / 400)              \
            - 32045                                                    \
          ) % 7];
    }
    
    int main(void) {
      printf("%d-%02d-%02d: %s\n", 2011, 5, 19, wd(2011, 5, 19));
      printf("%d-%02d-%02d: %s\n", 2038, 1, 19, wd(2038, 1, 19));
      return 0;
    }
    

    By removing the splicing and spaces from the return line in the wd() function, it can be compacted to a 286 character single line :)

提交回复
热议问题