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.

2 thoughts on “Get the Current Hour in Batch files”

  1. This does not work when the hour has only one character – e.g. 9am returns ” 9″ (with an empty space before the time)

Leave a Reply

Your email address will not be published. Required fields are marked *

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

All trademarks and copyrights on this page are owned by their respective owners. Quotes from linked articles are probably the property of the publications linked or the property of the person(s) quoted. The rest © 2001- 2024 by James A. Chappell