In batch scripting, generating file and directory names with current date and time stamps can greatly enhance organization and workflow. This tutorial will walk you through various code snippets and techniques to format date and time in a batch script. By incorporating these methods, you can efficiently create time-stamped files and directories according to your desired format.
I required to make a batch script which needs file / directory to be created with current date / time stamps. Following are the code snippets for formatting date / time in a batch script:
Method 1: Extracting Date Components
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET MYDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %MYDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/" %%A IN ('echo %MYDATE%') DO SET yyyy=%%B
set DATED=%mm%%dd%%yyyy%
md %DATED: =%
Method 2: Regular Expressions for Date Manipulation
FOR /F "tokens=*" %%A IN ('DATE/T') DO SET MYDATE=%%A
#Using regular expresions to remove / and DAY
SET MYDATE=%MYDATE:/=%
SET MYDATE=%MYDATE:* =%
md %MYDATE%
Method 3: Extracting Date Components with Substring Operations
@echo off
set yy=%date:~-4%
set mm=%date:~-7,2%
set dd=%date:~-10,2%
set MYDATE=%yy%%mm%%dd%
Section 2: Formatting Time in Batch Script
Method 1: Parsing Hour and Minute Components
for /f "tokens=2-4 delims=/ " %%g in ('date /t') do (
set mm=%%h
set dd=%%g
set yy=%%i
)
set MYDATE=%yy%%mm%%dd%
Method 2: Utilizing the DATE /T Command
for /f "tokens=1-2 delims=: " %%j in ('time /t') do (
set hh=%%j
set mn=%%k
)
set MYTIME=%hh%%mn%
Section 3: Combining Date and Time To merge the date and time strings obtained from the previous sections, you can use concatenation to form custom file and directory names that include both the date and time stamps.
Conclusion: By mastering the techniques shared in this tutorial, you can now create batch scripts that generate file and directory names with accurate and formatted date and time stamps. Incorporating these methods will streamline your workflow and enhance organization, ensuring that your files and directories are properly labeled with time-stamped information. Use these code snippets to enhance your batch scripting projects and boost productivity.