I searched SO, but could find answers using programming languages like Java, Python, JS, etc. I'm trying to find the next month last date when a relative date is given as input to the awk. Looking for awk implementation.
Here is my logic, but it breaks for different inputs.
$ export DT="2020-12-31"
$ awk -v dt=$DT ' BEGIN { gsub(/-/," ",dt); print dt;dt2=mktime(dt " 0 0 0");
while(c<2) { dd=strftime("%d",dt2+(i++)*86400);if(dd*1==1)c++;} ; print strftime("%F",dt2+(i-2)*86400) } '
2020 12 31
2021-01-31 # Correct
Below one is giving wrong answer
$ export DT="2020-01-01"
$ awk -v dt=$DT ' BEGIN { gsub(/-/," ",dt); print dt;dt2=mktime(dt " 0 0 0");
while(c<2) { dd=strftime("%d",dt2+(i++)*86400);if(dd*1==1)c++;} ; print strftime("%F",dt2+(i-2)*86400) } '
2020 01 01
2020-01-31 # Wrong - Should be 2020-02-29
what is wrong with the logic?. I welcome other awk solutions
In a similar way, I need to calculate prior-month start & end dates, relative month start and end date, next month's start and end date in a robust way using awk.
Below is the code for previous month end date
$ awk -v dt="2021-01-30" ' BEGIN { gsub(/-/," ",dt); print dt;dt2=mktime(dt " 0 0 0");
dy=strftime("%d",dt2); print strftime("%F",dt2-dy*86400) } '
2021 01 30
2020-12-31