views:

2483

answers:

3

I need to write a bat file which creates a new folder using current date and time for folder name. I came up with the following:

for /f "tokens=1-3 delims=:," %%i in ("%TIME%") do md %DATE%-%%i.%%j.%%k

Does this code has any flaws? Is there an easier / more natural way to do it?

+2  A: 

I use this bat

for /F "tokens=1-4 delims=. " %%i in ('date /t') do (
set Day=%%i
set Month=%%j
set Year=%%k
)

for /F "tokens=1-4 delims=: " %%i in ('time /t') do (
set Hour=%%i
set Minute=%%j
set Second=%%k
)


md %1\%Year%-%Month%-%Day%

Hope it helps.

lopkiju
Note that time /t won't work if command extensions are disabled, but I guess this doesn't really bother you. (See http://www.pc1news.com/disabling-command-processor-extensions-824.html for reference)
schnaader
I don't know much about bat scripting, I just wanted bat that creates a folder with current date, but thank you for the information.
lopkiju
A: 

Have you tried it? Your command line throws an error on my side.

dirkgently
If you want to run it directly from the command line instead of a batch file, replace %%i with %i, then it will work.
schnaader
I tried it inside a bat file. It seems to work fine. When you run it from command line you should replace %% with %.for /f "tokens=1-3 delims=:," %i in ("%TIME%") do md %DATE%-%i.%j.%k
Yarik
right. thanks schnaader and yarik.
dirkgently
+1  A: 

You can use substring and the built in %DATE% and %TIME% variables to do this:

@echo OFF

:: Use date /t and time /t from command line to get format of your date and
:: time; change substring below as needed.

:: This will create a timestamp like yyyy-mm-yy-hh-mm-ss.
set TIMESTAMP=%DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2%-%TIME:~0,2%-%TIME:~3,2%-%TIME:~6,2%

@echo TIMESTAMP=%TIMESTAMP%

:: Create new directory
md "%1\%TIMESTAMP%"
Patrick Cuff
that's exactly what I was looking for, this approach seems more natural to me
Yarik