日期到星期几算法
Date to Day of the week algorithm?
给定日、月、年,返回一周中的某一天的算法是什么?
这可以使用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';
最简单的算法之一是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的倍数。
相关文章:
- 查询SQLite数据库中的日期
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- Log4cpp:以UTC/GMT时区打印日期
- 算法问题:查找从堆栈中弹出的所有序列
- 下面是排序算法O(n)吗
- KMP算法和LPS表构造的运行时间
- 为什么我的排序算法会更改数组值
- 求最大元素位置的分治算法
- 使用C++的日期库读取时间
- 具有非整数边容量的最大流量的Dinic算法
- 用于在C++中将串行日期 (Excel) 转换为年-月-日的算法
- [C++]向抽象日期添加天数的算法,例如,年有13个月,第13个月有40天
- 日期到星期几算法