如何将时间添加到 Windows 批处理命令 %time% 输出?

How do I add time to a Windows batch command %time% output?

我有一个将在 4 小时内循环的批处理文件。我想显示 4 小时(或 14400 秒)后的时间。

@echo off
cls

title My Batch File

set looptime=14400

:loopme

set nextlooptime=%time%+%looptime%    

echo This command prompt will loop in 4 hours, at %nextlooptime%.

TIMEOUT /T %looptime% /NOBREAK

goto loopme

输出不符合预期。

"此命令提示符将在 4 小时后循环,在 10:51:09.62+14400.

等待 13656 秒,按 CTRL+C 退出..."

我希望它显示从 %time%开始 4 小时(或 14400 秒)的时间。

我该如何实现?

您可以很容易地调用 Powershell 将小时数添加到当前时间并将其放入变量中。

for /f "delims=" %%G IN ('powershell "(get-date %time%).AddHours(4).ToString('HH:mm:ss')"') do set endtime=%%G

这是我的方法。假设仅打算向用户显示,seconds/milliseconds 已被排除。

@echo off & color f0

:[ Retrieve the hours and minutes from the %time% variable and turn it into variables ]
set hour=%time:~0,2%
  if "%hour:~,1%"=="0" set hour=%hour:~1,2%
set minute=%time:~3,2%
:[ Being careful of leading zeros in set /a, as it indicates an octal value ]
  if "%minute:~,1%"=="0" set minute=%minute:~1,2%
:[ Here is where 4 hours are added ]
set /a hour+=4
:[ Minding the run over time ]
  if %minute% geq 60 set /a minute=%minute%-60 && set /a hour=%hour%+1
  if %hour% geq 24 set hour=00
  if %minute% lss 10 set minute=%minute%
  if %hour% lss 10 set hour=0%hour:~1,1%
echo Task will run at %hour%:%minute%
:[ If desired display is relative to 12; ]
  if %hour% gtr 12 set /a hour-=12
echo Alt display is %hour%:%minute%
pause

:[ Here is where 4 hours are added ]后面的set /a可以随意调整。

当然,如果需要灵活性,可以使用 set /a hour+=%addTime%