简体   繁体   中英

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.

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

Batch files are not good in date/time operations. Spend much time with similar issues, I can recommend to use external tool such (as window port of unix 'date' command for example) and perform any operations on timestamps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM