Friday 18 July 2008

Batch Programming Tip#10: Making and calling a subroutine (part 2)

Let's see how can pass arguments to our get_date subroutine to change date format. For instance, we will be able to choose whether the day or month comes first in our output string and which separator (if any) we wish to use.
Beware that date /T is probably locale dependent. On my system the date is output in the following format 'day. dd/mm/yyyy' e.g. mon. 14/07/2008


@echo off

:show_date
call :get_date / 0 1
echo Date: %_date%
goto eof

:get_date
set delim=%~1
set order=%~2
set show_day=%~3

echo delim=%delim% and order=%order% and show_day=%show_day%

for /F "tokens=1,2,3,4 delims=/ " %%d in ('date /T') do (
set day=%%d
set dd=%%e
set mm=%%f
set yyyy=%%g
)

set _date=%dd%%delim%%mm%%delim%%yyyy%
if "%order%"=="1" set _date=%mm%%delim%%dd%%delim%%yyyy%
if "%show_day%"=="1" set _date=%day% %_date%
goto blackhole

:eof
echo Press any key to quit...
pause > NUL
goto blackhole

:blackhole


The get_date subroutine has changed considerably.

First, we get three possible arguments: delimiter, order (either day/month or month/day) and show_day (whether or not to show the day: 'mon.' for instance). You retrieve the arguments in the same way as you would for batch command-line arguments (using %~1, etc.).

These arguments are appended to the call to the subroutine: call :get_date / 0 1.

Second, we split the date string into four parts day (mon.), dd (14), mm (07), yyyy (2008).

Finally, we build the %_date% variable while taking into account the various arguments. If %order% is set to 1 we reverse dd and mm order. If show_day is set to 1, we prefix the date with the day.

That's it.

Thoughts?

No comments:

Online Marketing
Add blog to our blog directory blog search directory Blog Directory Blogarama - The Blog Directory