Get the Current Hour in Batch files

(from the I dislike Windows slightly less than I used to dept.)

In a project I’m working on, I needed a way to get the current hour from within a Windows batch file. This sort of thing is trivial on Unix like systems (or using Cygwin with Windows, which wasn’t an option in this case).

Poking around the web, I found the solution here.

The short answer:

In the above code snippet, hr will be set to the current hour.

The long answer:

The “:~” characters tell the batch file to return a subset of data from the variable. The number that immediately follows :~ is the character position to start with, and the first character in the string is always 0. So %TIME:~0% is functionally equivalent to %TIME%. Optionaly after the number can be a comma followed by another number, indicating how many characters to include. So the reference %TIME:~3,2% tells the batch file to return two characters starting at position 3 from the current time. In other words, the two characters that represent the current minute.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.