2

trying to replace 11/22/2016 to 11222016. for this I have tried the following and is working as expected.

set string=dd/mm/yyyy.
set find=/
set replace=
call set string=%%string:!find!=!replace!%%
echo %string%

output is ddmmyyyy

but when I tried this in the if condition this is not working as expected.

setlocal enabledelayedexpansion

    set isDateFound=false
    set string=dd/mm/yyyy.
    if "%isDateFound%" == "false" (
    echo %isDateFound%
    set find=/
    set replace=
    call set string=%%string:!find!=!replace!%%
    echo %string%
    )

output dd/mm/yyyy

looks like the delayedexpressions is playing some role here. but I am not able to overcome this. How replace substring in side the if condition.

1
  • 1
    Odd that you used delayed expansion for the find and replace variable but not the string variable. Why would you think you would not need it for the string variable? Commented Feb 15, 2016 at 17:46

2 Answers 2

2

Here is a better way to do that :

@echo off
FOR /F "tokens=1-3" %%a IN ('WMIC Path Win32_LocalTime Get Day^,Month^,Year ^| findstr [0-9]') DO (
    set "$Day=0%%a"
    set "$Month=0%%b"
    set "$Year=%%c"
 )

echo %$Year%%$Month:~-2%%$Day:~-2%

The leading 0 before before Month and Day is automatically added.

Sign up to request clarification or add additional context in comments.

Comments

1

You are using delayed expansion in your set call so in this case you need to access the value via !string! not %string%, so:

setlocal enabledelayedexpansion

set isDateFound=false
set string=dd/mm/yyyy.
if "%isDateFound%" == "false" (
echo %isDateFound%
set find=/
set replace=
call set string=%%string:!find!=!replace!%%
echo !string!
)

note echo !string! instead of echo %string%

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.