Search the Site


bottom corner

Format Windows command line date

This note briefly describes how to format the date in the Windows command line environment.

This page is filed under keyword(s): windows.

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:\windows\system32\xcopy.exe /c /d /e /h /r /y
set dt=%date:~10,4%%date:~4,2%%date:~7,2%
%backupcmd% C:\stuff\*%dt%.txt D:\backup\stuff\

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): windows.
Author: C. Peter Chen
Last updated: 4 Mar 2010

bottom corner