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%

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

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

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

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

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

2 Replies to “Format Windows command line date”

    1. Thanks for visiting Dev-Notes, Len. This how string parsing works in Windows command line, assuming your variable is named %date%:

      %date:~10,4% – Start with the 10th character of the string, and include the subsequent 4 characters of the string.

      This thus gives us the year value out of our previously stated example of “Wed 10/08/2008”.

      Also, please keep in mind that when counting characters you should start with 0 rather than 1.

      Thanks again.

Leave a Reply

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