我正在尝试获取上个月的最后一天,并在批处理文件中设置一个变量。
例如,如果今天的日期是2016-10-18我希望我的变量设置为2016-09-30
答案 0 :(得分:0)
一种方法是用不同的语言写一些内容,以便将日期回显到stdout。任何语言都可以,但这是VBS中的一个实现
' Save this as LastDayOfLastMonth.vbs
Function Pad(Value, PadCharacter, Length)
Pad = Right(String(Length,PadCharacter) & Value, Length)
End Function
Dim Today
Today = Date
FirstOfMonth = DateSerial(Year(Today), Month(Today), 1)
WScript.Echo FirstOfMonth
LastOfPreviousMonth = DateAdd("d", -1, FirstOfMonth)
WScript.Echo Pad(Year(LastOfPreviousMonth), "0", 4) & "-" & _
Pad(Month(LastOfPreviousMonth), "0", 2) & "-" & _
Pad(Day(LastOfPreviousMonth), "0", 2)
然后从您的批处理文件中调用它:
@echo off
FOR /F %%i IN ('cscript "%~dp0LastDayOfLastMonth.vbs" //Nologo') do SET MYDATE=%%i
echo %MYDATE%
答案 1 :(得分:0)
@echo off
setlocal enableextensions enabledelayedexpansion
call :getPreviousMonthLastDate lastDay
echo %lastDay%
exit /b
:getPreviousMonthLastDate returnVar
setlocal enableextensions disabledelayedexpansion
set "y=" & for /f "tokens=1-2 delims=/" %%a in ('
robocopy "|" . /njh
') do if not defined y set /a "y=%%a", "m=1%%b-100"
if %m% equ 1 ( set /a "y-=1" , "m=12", "d=31" ) else (
set /a "m-=1", "d=30+((m+m/8) %% 2)", "m+=100"
if %m% equ 3 set /a "d=d-2+!(y%%4)-!(y%%100)+!(y%%400)"
)
endlocal & set "%~1=%y%-%m:~-2%-%d:~-2%" & exit /b
除此之外,代码使用robocopy
命令生成错误并以与语言环境无关的方式检索当前日期。您可以使用任何其他可用方法替换它并保留其余的计算,但y
必须包含yyyy
格式的年份,m
必须包含月份编号而不留下零填充。