UPDATE 1 : Function code further streamlined to minimize redundant calculations.
Unless you insist on shell-only purity, here's a fully POSIX
-compliant awk
-based solution that has built-in leap year calculation while COMPLETELY avoiding the need of any lookup tables or reference strings.
Unlike other suggested solutions, for months other than February, modulo op is only performed once instead of twice by replacing
(mm - 1) % 7 % 2
with
(odd month) XNOR (before August)
jot -w '2023 %d' 12 | awk '!_; ++$!_' | gsort -k 1,1n -k 2,2n |
function monyear2numdays(__, ___, _) {
return ((__ = +__) % (_ += _ ^= _<_) == (__++ < _^++_)) + _^_ \
+ (_ - __ ? _ : --__^(___ == "" || (___ = +___) % ++_ \
? !_ : ___ % (_ *= _ * ++_) || ___ % (__ * _ * __) == !_))
}
awk '$++NF = monyear2numdays($2, $1)'
2023 1 31 2024 1 31
2023 2 28 2024 2 29
2023 3 31 2024 3 31
2023 4 30 2024 4 30
2023 5 31 2024 5 31
2023 6 30 2024 6 30
2023 7 31 2024 7 31
2023 8 31 2024 8 31
2023 9 30 2024 9 30
2023 10 31 2024 10 31
2023 11 30 2024 11 30
2023 12 31 2024 12 31
Month field (__
) values beyond [1, 12]
yield meaningless results. The year field (___
) is optional. Empty year inputs defaults to common year values. Zero-padded YYYY
values are accepted but completely optional.
The function only requires 1 extra temp variable on top of the 2 mandatory ones for accepting user input to calculate all necessary constants, thresholds, offsets, and leap-year logic on-the-fly.
If, instead, you have a pre-made leap year indicator boolean flag ("y"
), then this tiny tiny expression is all you need to calculate number of days
27+(m-2?(m<8~m%2)+3:m^y)
— m^y
is exponentiation