0

How does one prints the current time in a batch file script?

I've seen the webpages:

  1. windows batch script format date and time
  2. TIME command

But neither are good:
With the 1st, using the variable %TIME%, it prints the same time - the time isn't changing.
With the 2nd, using the command TIME, it doesn't print the seconds.

The code in the batch file is:

@echo OFF
for /l %%x in (1, 1, 100) do (
    echo "*** Repeat no. %%x ***"
    echo "%TIME%"

    REM Executing some commands here which take about 5 seconds

    for /l %%i in (1, 1, 20) do (
        echo "-- %%i:"
        echo "%TIME%"
            REM Executing a command here which take about 1 second
    )
)

I can't believe that a google search didn't solve this for me!

Community
  • 1
  • 1
Dor
  • 7,344
  • 4
  • 32
  • 45
  • Can you show your code? The behaviour described is usually associated to delayed expansion, but without code ... – MC ND Jun 16 '14 at 11:36

1 Answers1

1
@echo OFF
    setlocal enableextensions enabledelayedexpansion
    for /l %%x in (1, 1, 100) do (
        echo "*** Repeat no. %%x ***"
        echo "!TIME!"

        REM Executing some commands here which take about 5 seconds

        for /l %%i in (1, 1, 20) do (
            echo "-- %%i:"
            echo "!TIME!"
                REM Executing a command here which take about 1 second
        )
    )

Yes, your problem is delayed expansion

When a line or a block (code inside parenthesis) is parsed, all variable reads are replaced with the value inside the variable before start to execute the code. So, any changes in the value of the variable during execution of the block are not visible since all variable reads where replaced with the values.

To solve it, you need to enable delayed expansion. This allows you to change the way you reference variables in code, changing (where needed) syntax from %var% to !var! to indicate the parser that the variable expansion need to be delayed until execution.

MC ND
  • 69,615
  • 8
  • 84
  • 126