Hi all,
If you use a windows server and get yesterday’s date for something like a download, you might probably use this popular script that can be found here and there. Unfortunately, the script is somewhat broken when dealing with getting the last day of the month. The logic is solid, but somewhere between the idea and implementation, something was lost.
see below the working, correct version:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
@setlocal enableextensions enabledelayedexpansion rem Get the date from WMI (on one line). for /f "skip=2 tokens=2-7 delims=," %%A in ('wmic path win32_localtime get day^,month^,year^ /format:csv') do ( set /a "yest_yyyy = %%C" set /a "yest_mm = %%B" set /a "yest_dd = %%A" ) rem Not the first of the month, just decrement day. if not %yest_dd%==1 ( set /a yest_dd = yest_dd - 1 goto done ) rem Jan 1, set to Dec 31 previous year. if %yest_mm%==1 ( set /a "yest_dd = 31" set /a "yest_mm = 12" set /a "yest_yyyy = yest_yyyy - 1" goto :done ) rem Any other day, decrement month. set /a "yest_mm = yest_mm - 1" rem Need to find last day, default to 31. set dim=31 rem Apr/Jun/Sep/Nov all have 30 days. Feb gets special handling. if %yest_mm%==4 set dim=30 if %yest_mm%==6 set dim=30 if %yest_mm%==9 set dim=30 if %yest_mm%==11 set dim=30 if not %yest_mm%==2 goto :got_dim rem Default Feb to 28 then use rules to override. set dim=28 set /a "divid=yest_yyyy%%400" if "%divid%"=="0" goto daysinmonth_29days set /a "divid=yest_yyyy%%100" if "%divid%"=="0" goto :done set /a "divid=yest_yyyy%%4" if not "%divid%"=="0" goto :got_dim rem Adjust to 29 days. :daysinmonth_29days set dim=29 :got_dim set yest_dd=%dim% :done rem Pad out and return value. if %yest_mm% lss 10 set yest_mm=0%yest_mm% if %yest_dd% lss 10 set yest_dd=0%yest_dd% set yesterday=%yest_yyyy%-%yest_mm%-%yest_dd% endlocal && set yesterday=%yesterday% |