【问题标题】:C - How to get dates in a week from only weeknumber and year?C - 如何仅从周数和年份获取一周内的日期?
【发布时间】:2021-12-25 11:08:27
【问题描述】:

我希望该函数返回一个字符串数组,其中每个日期表示为“13/11”或我可以从中提取日期和月份的任何其他格式。
也许它看起来像这样:

char** get_dates_from_year_and_week(int year, int week) {
    //Magic happens
    return arr
}
get_dates_from_year_and_week(2021, 45);
//Would return ["08/11", "09/11", 10/11", "11/11", "12/11", "13/11", "14/11"];

如何使用 c 来实现这一点?欢迎任何图书馆。

【问题讨论】:

  • 使用日期和时间函数,例如mktimelocaltimestrftime。您可以仅使用年份字段从struct tm 开始(请注意,它是年份减去 1900)。然后使用mktime 转换为time_t。然后通过将一周中的秒数 (7 * 24 * 60 * 60) 乘以周数来估算周数。您使用localtime 转换回struct tm。然后您可以使用strftime 将日期设置为良好的格式。请注意,strftime 有一个星期数选项,因此您可以检查您的计算是否正确。

标签: c time


【解决方案1】:

要将年/周/(星期几)转换为年/月/日,请找到一年中第一个星期一的日期为 ISO 8601 week-of-the-year 开始于一个星期一。然后添加week*7days。使用 mktime() 确定星期几(从星期日开始)并将超出范围的日期带入其主要范围。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct {
  int year, month, day;
} ymd;

typedef struct {
  int year, week, dow; // ISO week-date: year, week 1-52,53, day-of-the-week 1-7
} ISO_week_date;

int ISO_week_date_to_ymd(ymd *y, const ISO_week_date *x) {
  // Set to noon, Jan 4 of the year.
  // Jan 4 is always in the 1st week of the year
  struct tm tm = {.tm_year = x->year - 1900, .tm_mon = 0, .tm_mday = 4,
      .tm_hour = 12};
  // Use mktime() to find the day-of-the week
  if (mktime(&tm) == -1) {
    return -1;
  }
  // Sunday to Jan 4
  int DaysSinceSunday = tm.tm_wday;
  // Monday to Jan 4
  int DaysSinceMonday = (DaysSinceSunday + (7 - 1)) % 7;
  tm.tm_mday += (x->dow - 1) + (x->week - 1) * 7 - DaysSinceMonday;
  if (mktime(&tm) == -1) {
    return -1;
  }
  y->year = tm.tm_year + 1900;
  y->month = tm.tm_mon + 1;
  y->day = tm.tm_mday;
  return 0;
}

"array of strings" --> 把那部分留给 OP 去做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2018-02-17
    • 1970-01-01
    相关资源
    最近更新 更多