Formatting date in MS-DOS batch file

I needed to make a simple MS-DOS backupscript in Windows XP today and the files were supposed to be stored in folders named by the current date, ISO style.

I ended up formatting the date using the following command

echo %date:~6,8%-%date:~3,2%-%date:~0,2%

Output

2007-10-02

The script

@echo off
REM Declare variables
Set TODAYSDATE=%date:~6,8%-%date:~3,2%-%date:~0,2%
Set DATADRIVE=c:
Set DATAFOLDER=Temp
Set BACKUPDRIVE=c:
Set BACKUPFOLDER=Backup

REM Make Backup folders
mkdir %BACKUPFOLDER%
mkdir %BACKUPFOLDER%%TODAYSDATE%

REM Copy files to todays backup folder
xcopy /e /v /c /f /h /z /y %DATADRIVE%%DATAFOLDER%* %BACKUPDRIVE%%BACKUPFOLDER%%TODAYSDATE%

The script creates a backup folder and copies files from a datafolder and stores them in todays backupfolder.

Do note that the date command prints the date in the format DD.MM.YYY, 02.10.2007

This script has been run on a daily basis through Windows Scheduler.

One thought on “Formatting date in MS-DOS batch file

  1. It looks like this is probably locale-specific, unfortunately. On my machine (Windows XP, US-English), I used this to print the date:

    echo %date:~10,4%-%date:~4,2%-%date:~7,2%

    Result:

    2012-10-30

Comments are closed.