【问题标题】:How do I add time to a Windows batch command %time% output?如何将时间添加到 Windows 批处理命令 %time% 输出?
【发布时间】:2015-11-12 16:11:52
【问题描述】:

我有一个将在 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 秒)时间。

我将如何实现这一目标?

【问题讨论】:

  • 您不能批量计算时间或日期。您可以使用set /a 进行(有限)计算。基本上,您需要将时间戳转换为纯整数(秒数),添加循环时间并将生成的整数转换回时间戳。

标签: windows batch-file time command prompt


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这是我的方法。假设意图只是向用户显示,则省略了秒/毫秒。

    @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可以调整为will。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      相关资源
      最近更新 更多