Tuesday, June 15, 2010

Extract %time% in Batch Programming

Hi Friends,

Date & Time are two very sensitive information which we need to extract frequently which doing any batch scripting for administrative purpose.

While, i already covered a article regarding how to correctly extract %date%, lets focus on how to extract %time% ;-)

Well, for the record, %time% variable holds information uniformly across all Windows Version. Which is good as we can easily extract our information as per needs.

But wait, there is a catch! No matter what you do & instruct your regional settings to include a leading "0" (zero) before the hour, silly DOS will always fail to do so for time prior to 10:00 am!

So lets evaluate how to extract %time%:
A simple way is like below:
@set time_temp=%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
@echo %time_temp%

This will work correctly only for time after 10:00 am as before 10:00 am, the %time% variable has value somewhat as:
C:\>echo %time%

As you can see, DOS fails to append a leading zero for your hour :-(
This makes my first approach fail instantly!

So how to go around & fix this problem?

As you can see, we simply but a check that if the extracted hour information is having the leading zero available or not...
If not, we are forcing one in the variable :-)

This should resolve your %time% extracting woes in batch programming!
If you have similar issues for extracting %date%, checkout how to extract %date%!

how to extract %time%, extract %time%, batch file commands, batch file command, bat files, bat file, batch files, batch script, batch scripting, batch program, windows scripting, windows scripts, DOS, %time%, Leading Zero, etc

1 comment:

Anonymous said...

Replace the space with a zero:

SET hh=%hh: =0%