批处理bat计算上个月最后一天的日期
【方案一】BAT + date.exe(GNU)
@echo off
rem 调用GNU for Win32的date.exe
set "gnuDate=C:/test/date.exe"
for /f %%a in ('%gnuDate% "+%%Y%%m01"') do (
for /f %%h in ('%gnuDate% -d "%%a 1 days ago" "+%%Y-%%m-%%d"') do (
set "DstDate=%%h"
)
)
echo,%DstDate%
pause
【方案二】BAT + VBS
@echo off
>"%temp%/DateCalculate.vbs" echo strLastDate=DateAdd("d", -DatePart("d", Date), Date)
>>"%temp%/DateCalculate.vbs" echo strFmtDate=Right(Year(strLastDate),4) ^& Right("0" ^& Month(strLastDate),2) ^& Right("0" ^& Day(strLastDate),2)
>>"%temp%/DateCalculate.vbs" echo WScript.Echo strFmtDate
for /f %%a in ('cscript /nologo "%temp%/DateCalculate.vbs"') do (
set "DstDate=%%a"
)
set DstDate=%DstDate:~0,4%-%DstDate:~4,2%-%DstDate:~6,2%
echo,%DstDate%
pause
【方案三】BAT
@echo off
setlocal enabledelayedexpansion
rem 假设系统日期格式为yyyy-mm-dd
set "y=%date:~0,4%"
set "m=%date:~5,2%"
set /a "m=1!m!-101, m=m+(^!m)*12"
rem 上月是否2月或小月
set /a "f=^!(m-2), s=^!(m-4)|^!(m-6)|^!(m-9)|^!(m-11)"
rem 今年是否闰年
set /a "leap=^!(y%%4) & ^!^!(y%%100) | ^!(y%%400)"
rem 上月有!d!天
set /a "d=f*(28+leap)+s*30+(^!f&^!s)*31"
set /a "y1=y-^!(m-12)"
set "m=0!m!"
set "m=!m:~-2!"
set "d=0!d!"
set "d=!d:~-2!"
set DstDate=!y1!-!m!-!d!
echo,%DstDate%
pause
【方案四】BAT + Ritchie Lawrence 日期函数
@echo off
rem 假设系统日期格式为yyyy-mm-dd
set ThisYear=%date:~0,4%
set ThisMonth=%date:~5,2%
call :DateToDays %ThisYear% %ThisMonth% 01 ThisDays
set /a DstDays=%ThisDays%-1
call :DaysToDate %DstDays% DstYear DstMonth DstDay
set DstDate=%DstYear%-%DstMonth%-%DstDay%
echo,%DstDate%
pause
goto :eof
:DateToDays %yy% %mm% %dd% days
setlocal ENABLEEXTENSIONS
set yy=%1&set mm=%2&set dd=%3
if 1%yy% LSS 200 if 1%yy% LSS 170 (set yy=20%yy%) else (set yy=19%yy%)
set /a dd=100%dd%%%100,mm=100%mm%%%100
set /a z=14-mm,z/=12,y=yy+4800-z,m=mm+12*z-3,j=153*m+2
set /a j=j/5+dd+y*365+y/4-y/100+y/400-2472633
endlocal&set %4=%j%&goto :EOF
:DaysToDate %days% yy mm dd
setlocal ENABLEEXTENSIONS
set /a a=%1+2472632,b=4*a+3,b/=146097,c=-b*146097,c/=4,c+=a
set /a d=4*c+3,d/=1461,e=-1461*d,e/=4,e+=c,m=5*e+2,m/=153,dd=153*m+2,dd/=5
set /a dd=-dd+e+1,mm=-m/10,mm*=12,mm+=m+3,yy=b*100+d-4800+m/10
(if %mm% LSS 10 set mm=0%mm%)&(if %dd% LSS 10 set dd=0%dd%)
endlocal&set %2=%yy%&set %3=%mm%&set %4=%dd%&goto :EOF