欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

批处理bat计算上个月最后一天的日期

程序员文章站 2022-03-22 16:25:32
【方案一】bat + date.exe(gnu) 复制代码 代码如下: @echo off rem 调用gnu for win32的date.exe set "gn...

【方案一】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