ChamingaD
ChamingaD

Reputation: 2928

Create Directory using Batch Script with Timestamp

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a-%%b)

set mydir="%mydate%-%mytime%"

mkdir %mydir%

With above batch script, I can create a directory name like 2015-05-14-11-30 AM

Now I need to convert the time into 24 format and remove AM/PM

Expected folder name - 2015-05-14-11-30

How to do it ?

Upvotes: 1

Views: 10977

Answers (2)

0m3r
0m3r

Reputation: 12499

lets make it simple & short

 @echo off

 set hh=%time:~-11,2%
 set /a hh=%hh%+100
 set hh=%hh:~1%
 Set mydir=%date:~10,4%-%date:~4,2%-%date:~7,2%-%hh%-%time:~3,2%-%time:~6,2%
 mkdir %mydir%

Upvotes: 1

Tarod
Tarod

Reputation: 7170

I think you should use the %TIME% pseudo-variable.

This is an example:

@echo off

For /f "tokens=1-4 delims=/:." %%a in ("%TIME%") do (
    SET HH24=%%a
    SET MI=%%b
    SET SS=%%c
    SET FF=%%d
)

For /f "tokens=1-2 delims=/,." %%a in ("%SS%") do (
    SET JUST_SS=%%a
)

echo HH24=%HH24%
echo MI=%MI%
echo SS=%SS%
echo FF=%FF%
echo JUST_SS=%JUST_SS%

echo mytime=%HH24%-%MI%-%JUST_SS%

Well, I realized HH24 has an empty space if the hour is less than 10, so here you have another solution, using %time:

SET HH=%time:~0,2%
if "%HH:~0,1%" == " " SET HH=0%HH:~1,1%
    echo HH=%HH%

SET MI=%time:~3,2%
if "%MI:~0,1%" == " " SET MI=0%MI:~1,1%
    echo MI=%MI%

SET SS=%time:~6,2%
if "%SS:~0,1%" == " " SET SS=0%SS:~1,1%
    echo SS=%SS%

Following the advice pointed out by @Stephan (TIME variable is dependent on region settings), we can use this approach:

@echo off

for /f "delims=" %%a in ('wmic OS get localdatetime  ^| find "."') do set datetime=%%a

set "YYYY=%datetime:~0,4%"
set "MM=%datetime:~4,2%"
set "DD=%datetime:~6,2%"
set "HH=%datetime:~8,2%"
set "MI=%datetime:~10,2%"
set "SS=%datetime:~12,2%"

set fullstamp=%YYYY%-%MM%-%DD%-%HH%-%MI%-%SS%
echo fullstamp=%fullstamp%

Upvotes: 7

Related Questions