【问题标题】:Date to Day of the week algorithm?日期到星期几算法?
【发布时间】:2011-08-13 11:00:59
【问题描述】:

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

【问题讨论】:

  • 在维基百科上:Calculating the day of the week.
  • 您可以在大约五秒钟内使用 Google 搜索。这是关于它的另一个问题:stackoverflow.com/questions/3017745/…
  • @hammar:大多数问题都可以在网站之外得到解答。这不是重点。
  • @Potatoswatter:我仍然认为在询问之前进行快速搜索是合理的。在这种情况下,Google 上的第一次点击就会找到答案。
  • @hammar:FAQ 没有提及简单的问题。如果你不想回答,那就不要。这不是重复的。

标签: c++ algorithm


【解决方案1】:

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

【讨论】:

  • +1 点赞。也投票重新提出这个问题。也许这是一个堆栈溢出重复,我不知道。但这是一个真正的 C++ 问题(被关闭为不是一个真正的问题),这是一个很好的答案。
  • 嗯,投了反对票。不知道为什么,但请注意 std::localtime 不是线程安全的。见this Q&A
  • 我知道它接受的答案,但不是他真正要求的答案。
【解决方案2】:

你需要一个起点。今天很好。对其进行硬编码。

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

警告:闰年每 4 年发生一次,但不是每 100 年发生一次,除非该年也是 400 的倍数。

【讨论】:

  • 我可以接受。硬编码完全没问题。
【解决方案3】:

对此最简单的算法之一是 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也很有帮助。

谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 2021-06-29
    相关资源
    最近更新 更多