Programming Tips - C/C++: Find current BYSETPOS (eg this is the third Tuesday of the month)

Date: 2022nov19 Language: C/C++ Keywords: iCal, iCalendar Q. C/C++: Find current BYSETPOS (eg this is the third Tuesday of the month) A. The iCal BYSETPOS has these values:
BYSETPOS=1 First weekday (eg Tuesday) of the month BYSETPOS=2 Second weekday of the month BYSETPOS=3 Third weekday of the month BYSETPOS=-1 Last weekday of the month
This is how we calculate that
#include <time.h> // Helper, is next week another month? // future1 is a copy so its ok to change it static bool isLastSetPos(const struct tm future1) { future1.tm_mday += 7; if (future1.tm_mday < 27) return false; if (future1.tm_mday > 31) return true; const time_t time = mktime(&future1); struct tm future2; localtime_r(&time, &future2); return future1.tm_mon != future2.tm_mon; } int calcSetpos(const struct tm *here) { if (isLastSetPos(here)) return -1; return here->tm_mday / 7 + 1; } // If you don't have the struct tm int calcSetpos() { time_t now = time(NULL); struct tm here; localtime_r(&now, &here); return calcSetpos(&here); }