datetimebatch-filewindows-7date-manipulation

batch file Subtracting hour current time on Windows


I need to subtract, for example, 1 hour from current time in a .bat file on Windows 7.

I do it like this.

set day=%date:~0,2%
set month=%date:~-7,2%
set year=%date:~-4,4%
:: ———————————————————————–
set hour=%time:~0,2%

set /A hour= hour - 1

if %hour% lss 0 set hour=23
if %hour% lss 10 set hour=0%hour%

echo %year%-%month%-%day% %hour%:00

But the problem, it is get consistence when the subtracting results a day before on a month before. For example, this date, 2016-03-01 00:05 I get 2016-03-01 23:05. I need to get 2016-02-29 23:05

I found several batch script to subtract one day, but nothing with hours or minutes.


Solution

  • It's not completely Batch, but I find that there are so many exceptions and special cases, that it's not worth it re-coding everything in Batch, especially when it's been done before. I like to just invoke Powershell from a batch file, like this.

    for /f "delims=" %%a in ('"powershell [DateTime]::Now.AddHours(-1).ToString('yyyy-MM-dd HH:mm')"') do echo %%a
    

    Output will be something like: 2016-10-18 02:05