Home > Software design >  C - How to get dates in a week from only weeknumber and year?
C - How to get dates in a week from only weeknumber and year?

Time:11-14

I would like the function to return an array of strings where each date is reprsented as "13/11" or any other format from where i can pull both the date and month.
Maybe it would look something like this:

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"];

How could this possible be obtained using c? Any library is welcome.

CodePudding user response:

To covert the year/week/(day-of-the-week) to a year/month/day, find the date of the first Monday of the year as ISO 8601 week-of-the-year begins on a Monday. Then add week*7 days to that. Use mktime() to determine day-of the-week (since Sunday) and to bring an out-of-range date into its primary range.

#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" --> leave that part for OP to do.

  • Related