Reputation: 75
I have a script that backup files from a folder to a new folder named with the current date and time, but the date does not display correct in the folder name.
Here is the code:
set hh=%time:~-11,2%
set /a hh=%hh%+100
set hh=%hh:~1%
Set dateseed=%date:~10,4%%date:~4,2%%date:~7,2%_%hh%%time:~3,2%%time:~6,2%
if not exist "C:\Temp\backup\%dateseed%" mkdir "C:\Temp\backup\%dateseed%"
cd "C:\Temp\backup\%dateseed%"
copy "C:\Temp\test2" .
The new folder is supposed to get a name like: 20140219_100105 but gets the name "-0-1_100115"
What is wrong?
Upvotes: 0
Views: 255
Reputation: 41234
The format of %date%
can be changed by the user and changes by default on different region settings so you can't rely on it for a range of machines.
Another issue is the calculation using hh
which will be treated as Octal numbers when the first digit is zero, and in such a case the calculation will fail with an error message when the number is not valid Octal such as 09
The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in XP Pro and higher.
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
Upvotes: 1