日复一日地获得当前

时间:2017-09-05 15:48:05

标签: windows batch-file cmd

我正在尝试获取StartDate(今天)和EndDate(昨天)。我一直试图保持数字格式正确的一天。然而,我注意到,当有一个前导零时系统不喜欢它并且当它从类似于" 09"中减去1时失败,但是对于" 10"完美地工作。我该怎么办呢?

echo off

REM CurrentDate (END DATE)      -------------------------------------------------------------
Set dd=%date:~4,2%
Set mm=%date:~7,2%
Set yyyy=%date:~10,4%
set END_DATE=%yyyy%-%mm%-%dd% 00:00 AM

echo %END_DATE%

REM CurrentDate - 1 (START DATE)  ------------------------------------------------------------
set m1dd=%date:~4,2%
set m1dd=09
echo %m1dd%
set /A m1dd -= 1
echo %m1dd%
Set m1dd=0%m1dd%
echo %m1dd%
Set m1dd=%m1dd:~-2%
echo %m1dd%
set START_DATE=%yyyy%-%mm%-%m1dd% 00:00 AM

echo %START_DATE%

pause

4 个答案:

答案 0 :(得分:1)

这个批处理文件使用XCOPY命令的一个小技巧来验证日期实际上是一个有效的日期,因为你从YYYYMMDD中减去1。

@echo off
setlocal
set rand=%random%
md "dummy%rand%\empty%rand%"

for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"

set /a y=%dt:~0,4%
set /a m=1%dt:~4,2%
set /a d=1%dt:~6,2%

REM set the number of days to substract
SET DAYS=1
FOR /L %%G IN (1,1,%days%) DO CALL :loop

set subdate=%y%%m:~-2%%d:~-2%
echo Today is: %dt:~0,8%
echo Yesterday was: %subdate%

rd /s /q "dummy%rand%"
pause
endlocal
GOTO :EOF

:loop
  set /a d-=1

  if %d% lss 101 (
    set d=131
    set /a m-=1

    if %m% lss 101 (
      set m=112
      set /a y-=1
    )
  )

xcopy /d:%m:~-2%-%d:~-2%-%y% /t "dummy%rand%\empty%rand%" "dummy%rand%" >nul 2>&1 || goto loop

GOTO :EOF

输出

Today is: 20170905
Yesterday was: 20170904
Press any key to continue . . .

答案 1 :(得分:1)

您可以使用批处理文件中的powershell:

timedelta

答案 2 :(得分:0)

您进行日期计算的方式并不理想。要获得更好的日期计算,您可以参考此link

如果您只是想快速修复以使当前代码运行,只需删除前导零,如下所示:

echo off

REM CurrentDate (END DATE)      -------------------------------------------------------------
Set dd=%date:~4,2%
Set mm=%date:~7,2%
Set yyyy=%date:~10,4%
set END_DATE=%yyyy%-%mm%-%dd% 00:00 AM

echo %END_DATE%

REM CurrentDate - 1 (START DATE)  ------------------------------------------------------------
set m1dd=%date:~4,2%
set m1dd=09
set /a m1dd=100%m1dd% %% 100
echo %m1dd%
set /a m1dd -= 1
echo %m1dd%
Set m1d=0%m1dd%
echo %m1dd%
Set m1d=%m1dd:~-2%
echo %m1dd%
set START_DATE=%yyyy%-%mm%-%m1dd% 00:00 AM

echo %START_DATE%

pause

答案 3 :(得分:-3)

我认为您应该将系统日期/时间格式修改为yyyy / MM / DD

Refer this post