Format Windows command line date

The need for me to format date in the Windows command line environment came up when I needed to write a batch file to automatically copy the latest copies of certain files in a large folder. The files are named in the format of ???YYYYMMDD.txt, which presented itself as one easy way for me to query for latest files.

Built in to Windows command line is the %date% variable, which displays the system date as follows based on my regional setting.

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:>echo %date%
Wed 10/08/2008

Please note that your regional settings might be different. For example, for those in Australia, the date might be presented in a DD/MM/YYYY format rather than the typical US MM/DD/YYYY format. If this is the case, you may wish to adjust the code below accordingly.

To suit my needs, I need to format this date to YYYYMMDD. Knowing that %date%’s format is consistent in format, we can just parse it as a string.

C:>echo %date:~10,4%
2008

C:>echo %date:~4,2%
10

C:>echo %date:~7,2%
08

Bringing it together, I will have the YYYYMMDD format I am looking for.

C:>echo %date:~10,4%%date:~4,2%%date:~7,2%
20081008

Once again, you may need to adjust the above command based on your own regional settings.

Here is how I put this code in action in the form of a batch file that copied only the files with today’s date.

set backupcmd=c:windowssystem32xcopy.exe /c /d /e /h /r /y
set dt=%date:~10,4%%date:~4,2%%date:~7,2%
%backupcmd% C:stuff*%dt%.txt D:backupstuff

Leave a Reply

Your email address will not be published. Required fields are marked *