日期到星期几算法

Date to Day of the week algorithm?

本文关键字:算法 日期      更新时间:2023-10-16

给定日、月、年,返回一周中的某一天的算法是什么?

这可以使用std::mktimestd::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';

最简单的算法之一是Tomohiko Sakamoto算法:

static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
y -= m < 3;
return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}

看看这个:https://iq.opengenus.org/tomohiko-sakamoto-algorithm/

我发现王的方法也很有趣

w = (d - d^(m) + y^ - y* + [y^/4 - y*/2] - 2( c mod 4)) mod 7

http://rmm.ludus-opuscula.org/PDF_Files/Wang_Day_5_8(3_2015)_high.pdf这个pdf也很有帮助。

谢谢!

你需要一个起点。今天天气很好。硬编码。

然后,您需要表示一个月中的天数。这是31 28 31 30 31 30 ... .因此,您可以开始对每一年的星期日数加减365 % 7,并再次减去(月差的天数总和)% 7。等等。

注意:闰年每4年出现一次,但不是每100年出现一次,除非那一年也是400的倍数。