I came across a bug in my DOS script that uses date and time data for file naming. The problem was I ended up with a gap because the time variable didn't automatically provide leading zero for hour < 10. So running> echo %time% gives back: ' 9:29:17.88'.
Does anyone know of a way to conditionally pad leading zeros to fix this?
More info: My filename set command is:
set logfile=C:\Temp\robolog_%date:~-4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log
which ends up being: C:\Temp\robolog_20100602_ 93208.log (for 9:23 in the morning).
This question is related to this one.
Thanks
A very simple way is to just replace the leading space with zero:
echo %TIME: =0%
outputs:
09:18:53,45
My Solution was to use the following idea:
Similar idea to Dennis' answer. The problem is that the width of
%time%
is always the same, so it inserts a space in the beginning instead of returning a shorter string.You can get rid of that with
for
:The rest is more or less the same, then.
Using Jesse's Contribution, I just created a variable with the modified output. Then I reference that variable to build the hour portion.
With the original source:
Thanks Jesse. I would have voted if I had the reputation points.
For the most compact solution implementing everything above, I think that
would work here without adding any new lines to the script. It's perhaps less elegant than multiple command solutions, though..
The following takes a few more lines but is clear and understandable. It saves stdout and stderr to separate files, each with a timestamp. The timestamp includes year, month, day, hour, minute, and second, in that order. Timestamps should always have the most significant date component first (year) and the least component (seconds) last. That enables files listings to be in time order. Without further ado, here is my solution.
This tacks a zero onto the beginning of the time and takes the last two digits of the hour (the minute and second start positions are shifted by one). So 3 AM becomes "03" then "03" and hour 15 becomes "015" then "15".
Less readably:
One line of code will do what you need:
For example, I use %Date% and then add a leading zero to a variable I use to determine if I need to replace the leading space with a zero for %Time%.
This creates a sortable timestamp and the second line makes sure there are no spaces for single digit hour, etc, to make it usable for scripts:
Output:
Thanks to help from above... This is what I am using:
I then have logs that are called out in Robocopy jobs like this:
There are many like this:
Ends job with this:
COMPLETE_LOG_2018-06-27_10_53_54.log
is the file produced at the end and it is sortable by file name.