Cmd batch scripting extract year month day from date and insert into path and file name

Many path and file names are named by date, for example you may have a folder named "2017", subfolders inside the folder are named with months like "01", "02", etc.You may need to do some daily routines which involves manipulating files with path or file name contains dates of that day. Instead of looking for the date information of that day and type them in command line or navigate through the directory trees, you can extract the year month or day from the output of "date" command and insert them into your string pattern to compose the path or file name.

The content of date command looks like this


To extract substring from the string in batch script, sepcify the start and length like the following


To extract year use %date:~0,4%

The following is an example that copy an image with folder name and file name with current day's date information inside to a destination

@echo off
set year=%date:~0,4%
set month=%date:~5,2%
set day=%date:~8,2%
echo copy D:\www\page\%year%-%month%\%day%\01\%year%%month%%day%01_brief.jpg D:\uploadfile\today-home-brief.jpg