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.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>




  



March 2010
M T W T F S S
« Feb    
1234567
891011121314
15161718192021
22232425262728
293031  

Statistics

There are currently 42 posts and 25 comments, contained within 13 categories.


Miscellaneous
- Source Files

Add to Technorati Favorites


Storage B
-OpenDDS 2.1.1
-OpenDDS 2.1
-It Proved Just Too Difficult
-Bridge Simulators
-C++0x FAQ
-Skepticism and standards of evidence applied development practices
-OpenDDS 2.0.1
-OpenDDS 2.0
-OpenDDS Version 1.3 Released
-LGPL License Option Added to Qt

Valid XHTML 1.0!

Valid CSS!