C - 如何仅从周数和年份获取一周内的日期?
C - How to get dates in a week from only weeknumber and year?
我希望函数 return 一个字符串数组,其中每个日期都表示为“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获得?欢迎任何图书馆。
要将 year/week/(day-of-the-week) 转换为 year/month/day,找到一年中第一个星期一的日期作为 ISO 8601 week-of -一年从星期一开始。然后加上 week*7
天。使用 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;
}
“字符串数组”--> 把那部分留给 OP 去做。
我希望函数 return 一个字符串数组,其中每个日期都表示为“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获得?欢迎任何图书馆。
要将 year/week/(day-of-the-week) 转换为 year/month/day,找到一年中第一个星期一的日期作为 ISO 8601 week-of -一年从星期一开始。然后加上 week*7
天。使用 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;
}
“字符串数组”--> 把那部分留给 OP 去做。