Get the Current Hour in Batch files

Filed under: Windows — jac @ September 5, 2006 - 7:39 am

(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:

set hr=%TIME:~0,2%

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.




  



September 2006
M T W T F S S
« Jul   Oct »
 123
45678910
11121314151617
18192021222324
252627282930  

Statistics

There are currently 32 posts and 22 comments, contained within 12 categories.


Miscellaneous
- Source Files

Add to Technorati Favorites


Storage B
-WordPress 2.7
-OpenDDS Version 1.2 Released
-FreeVMS
-OpenDDS Version 1.1 Released
-C++ functions to convert between decimal degrees and degrees, minutes, and seconds
-WordPress 2.5
-Multics
-C++ Functions to Evaluate Chebyshev Polynomials
-OpenDDS
-X Windows Programming in C++: Part III

Valid XHTML 1.0!

Valid CSS!