6

for /D %%A in () do "C:\Program Files\7-Zip\7z.exe" a -tzip "%%A.zip" -xr!.bat "%%A" -r -x!*.xls

The above batch will automatically zip the files in a directory.. While zipping I want to append date and time in a format (YYYYMMDD.HHMMSS).. For example,say the folder name is "University".If I run the batch file, the final zip name should create as "University_YYYYMMDD.HHMMSS.zip"..

user2991622
  • 63
  • 1
  • 1
  • 4
  • Similar question: [windows batch script format date and time](http://stackoverflow.com/questions/1192476/windows-batch-script-format-date-and-time) – Ilya Nov 15 '13 at 04:31
  • 1
    Be careful: the solutions using `%date%` and `%time%` are machine/locale specific and can change from one machine to another, or even when you change the regional settings on your own machine. Wmic can easily give you variables that are always the same format, and so can a VBS script with some calculations. – foxidrive Nov 15 '13 at 07:20
  • Most error-proof solution is in question @Ilya linked to - http://stackoverflow.com/a/16349176/198852 However, it is almost not voted :( – Serhii Kheilyk Nov 15 '13 at 09:10

2 Answers2

13

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 "fullstamp=%YYYY%%MM%%DD%.%HH%%Min%%Sec%"

for /D %%A in (*) do "C:\Program Files\7-Zip\7z.exe" a -tzip "%%A_%fullstamp%.zip" -xr!.bat "%%A" -r -x!*.xls
foxidrive
  • 40,353
  • 10
  • 53
  • 68
  • as WMIC was introduced in Windows 2000, this should work there as well. However, don't have one to check. – Serhii Kheilyk Nov 15 '13 at 09:01
  • 2
    @sergiykheylyk Thanks for your comment. FWIW WMIC isn't in XP Home, and I checked my W2K Pro and it doesn't have WMIC either by default. – foxidrive Nov 15 '13 at 10:10
0

Here is a solution to build your string:

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%

set year=%date:~-4%
echo year=%year%
set month=%date:~3,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
echo month=%month%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
echo day=%day%

set datetimef=%year%%month%%day%.%hour%%min%%secs%

echo datetimef=%datetimef%

So you can just concatenate variable %datetimef% with a name of output file:

for /D %%A in () do "C:\Program Files\7-Zip\7z.exe" a -tzip "%datetimef%_%%A.zip" -xr!.bat "%%A" -r -x!*.xls
Ilya
  • 4,583
  • 4
  • 26
  • 51