The current date value is often used in batch files to timestamp a log file. It is usually done by getting separated into YYYY
, MM, and DD. These values are then concatenated together and appended to a log file name.
This poses no problems because it is used as text.
However, if we want to use these values in calculations, we will get unexpected results if there is a leading zero. This
is because a leading zero in front of a number denotes it as an Octal number.
If the date was 5th August 2016, we can see that DD is 05, MM is 08, and YYYY is 2016.
If I need to calculate yesterday's date so I can pass yesterday's date into the XCOPY command so that it will copy everything from yesterday,
I will get unexpected results if the current date reaches 8th August.
To calculate yesterday's date, I would normally subtract one from DD. The code for that would normally look like this :
REM Assuming regional and date settings are: ddmmyyyy
@echo off
SetLocal EnableExtensions ENABLEDELAYEDEXPANSION
cls
set DD=%date:~4,2%
set MM=%date:~7,2%
set YYYY=%date:~10,4%
set /a yesterDD = %DD% - 1
echo !yesterDD!
xcopy "c:\source\" "c:\destination\" /D:%MM%-!yesterDD!-%YYYY% /S /Y
However, because any number with a leading zero will be treated as an Octal number, the results may not be what is expected.
Because I know that I will be dealing with DD and MM values, I wrote a simple DOS batch function that deals specifically
with those values and return a corresponding value without the leading zero.
The function looks like this :
REM FUNCTION
:ReturnWithoutZeroInFront
set returnNN=%~1
if /I %~1 EQU 01 set /a returnNN=1
if /I %~1 EQU 02 set /a returnNN=2
if /I %~1 EQU 03 set /a returnNN=3
if /I %~1 EQU 04 set /a returnNN=4
if /I %~1 EQU 05 set /a returnNN=5
if /I %~1 EQU 06 set /a returnNN=6
if /I %~1 EQU 07 set /a returnNN=7
if /I %~1 EQU 08 set /a returnNN=8
if /I %~1 EQU 09 set /a returnNN=9
goto :eof
We can use it in our original batch file by adding it and calling it like this :
REM Assuming regional and date settings are: ddmmyyyy
@echo off
SetLocal EnableExtensions ENABLEDELAYEDEXPANSION
cls
set DD=%date:~4,2%
set MM=%date:~7,2%
set YYYY=%date:~10,4%
call :ReturnWithoutZeroInFront %DD%
set /a yesterDD = !returnNN! - 1
echo !yesterDD!
xcopy "c:\source\" "c:\destination\" /D:%MM%-!yesterDD!-%YYYY% /S /Y
goto :eof
REM FUNCTION
:ReturnWithoutZeroInFront
set returnNN=%~1
if /I %~1 EQU 01 set /a returnNN=1
if /I %~1 EQU 02 set /a returnNN=2
if /I %~1 EQU 03 set /a returnNN=3
if /I %~1 EQU 04 set /a returnNN=4
if /I %~1 EQU 05 set /a returnNN=5
if /I %~1 EQU 06 set /a returnNN=6
if /I %~1 EQU 07 set /a returnNN=7
if /I %~1 EQU 08 set /a returnNN=8
if /I %~1 EQU 09 set /a returnNN=9
goto :eof