Batch Script Dates and Times
When working with dates and times in Batch Script the built in variables 'date' and 'time' can be used.
echo %date% echo %time%
This displays the date and time as follows.
03/09/2023 16:59:47.41
It should be noted that the date here is displayed in day, month, and year format, however, this may vary depending on system settings. The time also includes milliseconds.
In order to access individual components of a date and time, the Batch Script substring functionality can be utilised.
echo %date% echo %time% echo Day: %date:~0,2% echo Month: %date:~3,2% echo Year: %date:~6,4% echo Hours: %time:~0,2% echo Minutes: %time:~3,2% echo Seconds: %time:~6,2%
This will produce the following output.
03/09/2023 16:59:47.41 Day: 03 Month: 09 Year: 2023 Hours: 16 Minutes: 59 Seconds: 47
The different components of the date and time can also be assigned to variables for later use, for example, to construct the date and time as desired.
set day=%date:~0,2% set month=%date:~3,2% set year=%date:~6,4% set hours=%time:~0,2% set minutes=%time:~3,2% set seconds=%time:~6,2% echo Today's date and time is: %day%-%month%-%year% %hours%:%minutes%
This produces the following output.
Today's date and time is: 03-09-2023 16:59