Format date and time in a Windows batch script
Formatting Date and Time in a Windows Batch Script
So you're working with a Windows batch script and you need to format the current date and time for later use in file names and other purposes. You want to know how to include the time in the format, and specifically how to handle single-digit hours. Don't worry, we've got you covered!
The Initial Approach
Before diving into the solution, let's take a look at the initial code snippet provided:
echo %DATE%
echo %TIME%
set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%
echo %datetimef%
This code gives the following output:
28/07/2009
8:35:31.01
2009_07_28__ 8_36_01
As you can see, the date and time are extracted from the system variables %DATE%
and %TIME%
respectively. However, there is an issue with the format of the time portion. Let's proceed to the solution.
Handling Single-Digit Hours
To handle single-digit hours, we need to modify the code slightly. Instead of using %time:~0,2%
to extract the hour portion, we'll use the following approach:
IF "%TIME:~0,1%"==" " (
set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%_0%time:~1,1%_%time:~3,2%_%time:~6,2%
) ELSE (
set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%
)
This updated code snippet checks if the first character of %TIME%
(which represents the hour) is a space. If it is, it means that the hour is a single digit. In this case, we prepend a 0
to the hour portion using 0%time:~1,1%
. If the hour is already two digits, the original code continues to be used.
Running the modified code will give you the desired output:
2009_07_28__08_36_01
Wrap Up and Engage!
And there you have it! You now know how to format the date and time in a Windows batch script while handling single-digit hours. Feel free to use this technique to incorporate the formatted date and time into your file names, log entries, or any other part of your script.
Was this solution helpful? Do you have any other questions or cool batch script tricks to share? Let us know in the comments below! Keep learning and keep coding! 💻✨