如何在 C++ 中获取一年中的第一个星期日?

How to get the first Sunday of year in c++?

我试图获取今年第一个星期日的日期

int getFristSunday () {
    time_t rawtime;
    struct tm * timeinfo;
    time( &rawtime );
    timeinfo = localtime( &rawtime );
    timeinfo->tm_mon = 0;
    timeinfo->tm_wday = 0;
    mktime( timeinfo );
    return timeinfo->tm_yday ;
}

但我得到第一个星期四

Result

来自this mktime reference

time->tm_wday and time->tm_yday are ignored.

您必须将 timeinfo->tm_mday 设置为 1,然后在调用 mktime 后查看今天是哪一天,然后从那里向前计数。

使用这个 free, open-source, header-only C++11/14 library:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    std::cout << year_month_day{sun[1]/jan/2016} << '\n';
}

输出:

2016-01-03

year_month_day 对象有 year()month()day() 访问器。并且算法经过高度优化(不包含迭代循环)。

如果您更愿意编写自己的日期计算,here are the public domain calendrical algorithms 在上述日期库中使用。 link 直接转到描述如何找到 month/year 组合一周中第 N 天的部分。

在调用 mktime() 之前,需要设置除 tm_ydaytm_wday 之外的所有字段。显然我们需要为 1 月 1 日设置 tm_montm_mday

重要的是将 tm_hour 设置为中午 (12) and/or tm_isdst 为 -1 以确保重新计算的时间不受夏令时的影响。考虑一下如果当前时间接近午夜并且现在的 DST 设置与 1 月 1 日不同会发生什么。重新计算可能会将时间从 1 月 1 日推迟到 1 月 2 日或 12 月 31 日。

int getFirstSunday(void) {
  time_t rawtime;
  struct tm * timeinfo;
  time(&rawtime);
  timeinfo = localtime(&rawtime);

  timeinfo->tm_mon = 0;     // set to January which is 0 "Months since January"
  timeinfo->tm_mday = 1;    // Set to the 1st of the month

  timeinfo->tm_hour = 12;  // Set to avoid getting the wrong DST setting for Jan 1.
  timeinfo->tm_isdst = -1; // Set to avoid getting the wrong DST setting for Jan 1.

  if (mktime(timeinfo) == -1) return -1;
  int DaysSinceSundayForJan1 = timeinfo->tm_wday;  // days since Sunday — [0, 6]
  int DaysAfterJan1toNextSunday = 7 - DaysSinceSundayForJan1;
  int DaysAfterJan1toFirstSunday = DaysAfterJan1toNextSunday%7;
  // Convert to "day of the month"
  return DaysAfterJan1toFirstSunday + 1;
}