0

Problem: When using string substitution, it only works for the cleandate but not the cleantime variable.

set backupdate=%date:~10%%date:~4,-8%%date:~7,-5%
set cleandate=%backupdate: =%

set backuptime=%time:~0,2%%time:~3,-6%%time:~6,-3%
set cleantime=%backuptime: =% 

echo %cleandate%\Test
echo %cleantime%\Test
pause

Output:

C:\Users\Sveta\Desktop>echo 20180514\Test 
20180514\Test

C:\Users\Sveta\Desktop>echo 172317 \Test 
172317 \Test

%cleantime% still contains a space between the 172317 and \Test. How do I fix it?

  • 1. Use the `set` syntax `set "VAR=Value"` to avoid unintended trailing white-spaces without the quotes becoming part of the value. 2. `%DATE%` and `%TIME%` depend on the locale settings, hence take a look at this thread: [Windows batch: formatted date into variable](https://stackoverflow.com/q/10945572). – aschipfl May 15 '18 at 08:42

2 Answers2

0

There is a space at the end of set cleantime=%backuptime: =%. Remove that space and then you should be good to go.

The way I found there was a space was that I tried this on the command line:

C:\Users\test\Desktop>echo %time:~0,2%%time:~3,-6%%time:~6,-3%\Test

The result was:

164326\Test

That led me to think that there might be something odd going on with set cleantime. Upon closer inspection with Visual Studio Code's Toggle Render Whitespace function, I was able to see the extra space at the end.

zedfoxus
  • 28,612
  • 4
  • 47
  • 53
0

There's no need for that, as long as you're happy that your code will be used on only PC's using the same settings and locales, then just expand the variables properly in the first place:

@Echo Off
Set "BackupDate=%DATE:~-4%%DATE:~-7,2%%DATE:~-10,2%"
Set "BackupTime=%TIME:~,2%%TIME:~3,2%%TIME:~6,2%"
Echo %BackupDate%\Test
Echo %BackupTime%\Test
Compo
  • 30,301
  • 4
  • 20
  • 32