日期到星期几算法?
问题内容:
给定日,月和年,返回星期几的算法是什么?
问题答案:
可以使用std::mktime
和std::localtime
函数来完成。这些功能不仅是POSIX,而且是C
标准(C 03§20.5)要求的。
#include <ctime>
std::tm time_in = { 0, 0, 0, // second, minute, hour
4, 9, 1984 - 1900 }; // 1-based day, 0-based month, year since 1900
std::time_t time_temp = std::mktime( & time_in );
// the return value from localtime is a static global - do not call
// this function from more than one thread!
std::tm const *time_out = std::localtime( & time_temp );
std::cout << "I was born on (Sunday = 0) D.O.W. " << time_out->tm_wday << '\n';