TenMinuteTutor

Programming tutorials

Date based file names

When creating a backup, it is very useful is each backup is placed in a separate folder. This means that the backup you create today will not overwrite the backup you created yesterday, or last week, so if anything goes horribly wrong you will not lose everything. Strictly speaking this is an archive rather than a backup, but whatever you call it, it is good insurance.

Even better, if you create a unique folder name based on todays date you will always be able to find any specific backup you need.

Windows batch files provide a built in variable %date% which contains the current date, so we could try:

mkdir backup_%date%

which should create a backup folder with a name based on the date - shouldn’t it? Well unfortunately %date% provides a value like 01/01/2010 ()assuming today is 1 Jan 2010), so we would be creating a folder called backup_01/01/2010 which isn’t a valid name. What you would get instead is a messy tree of subfolders with your backup files all jumbled up.

Fortunately batch files have a special syntax for extracting substrings which can do can do this:

%date~0,2%

which is a special syntax for extracting a substring of a variable value - it extracts 2 characters, starting at character 0 (the first character). This is the first 01 of the date string in our example. The following ugly but hopefully intelligible syntax extracts the first 01, the second 01 and the final 2010 (or the equivalent values for whatever day it is today):

%date:~0,2%%date:~3,2%%date:~6,4%

giving a value 01012010. So:

set d=%date:~0,2%%date:~3,2%%date:~6,4%
mkdir backup_%d%

will create a folder called backup_01012010, and will create a different named folder every day.

From now on we can use the variable %d% as a base for any files or folders we need to create based on the date.

NOTE %date% is locale specific. You might need to look at what %date% returns in your locale and adjust the code if necessary.