DOS Command to get the 2 Digit HOUR, Minute, and Second

January 24, 2011

When you just need the current HOUR, MINUTE, SECOND in a batch file.

set hr=%TIME: =0%
set hr=%hr:~0,2%
echo %hr%

set min=%TIME:~3,2%
echo %min%

set sec=%TIME:~6,2%
echo %sec%

Here is how it works.

First off the hour. If you run echo %TIME% and it happens to be 7 AM, you’ll get ” 7″ Well that doesn’t work if you want the two digit format like “07”. To fix that I simply replaced a blank space with a zero, like so set hr=%TIME: =0%. If it is between the hours of 0-9 then it would look something like this “0 7”.

The Minute and Second share the same code, except it is already in two digit format so all it does is grabs the two digits and sets them to their respective vars.

+1 this post if it helped you!

4 comments on “DOS Command to get the 2 Digit HOUR, Minute, and Second

  1. Samit on said:

    It’s good but not perfect..it’s not working If time is 4:15:xx:xx like…………..it’s giving 4: as hr and 5: as min

    • larmib on said:

      I’m not having that issue using this script, here are my results from my Windows XP machine:
      C:\>set hr=0%TIME:~0,2%
      C:\>set hr=%hr: =%
      C:\>set hr=%hr:~-2%
      C:\>echo %hr%
      08
      C:\>set min=%TIME:~3,2%
      C:\>echo %min%
      46
      C:\>set sec=%TIME:~6,2%
      C:\>echo %sec%
      07
      C:\>echo %TIME%
      8:46:19.21
      ^ notice the space, it should be there by default.

  2. bennewcomb on said:

    Wouldn’t this be more straight forward?

    set hr=%TIME: =0%
    set hr=%hr:~0,2%

Leave a Reply