In a Windows (Windows XP) batch script I need to format the current date and time for later use in files names, etc.
It is similar to Stack Overflow question How to append a date in batch files, but with time in as well.
I have this so far:
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%
which gives:
28/07/2009
8:35:31.01
2009_07_28__ 8_36_01
Is there a way I can allow for a single digit hour in %TIME%, so I can get the following?
2009_07_28__08_36_01
Create a file called "search_files.bat" and place the contents below into the file. Then double click it. The temporary %THH% variable was put in place to handle the AM appropriately. If there is a 0 in the first 2 digits of the time, Windows ignores the rest of the file name of the LOG file.
As has been noted, parsing the date and time is only useful if you know the format being used by the current user (for example, MM/dd/yy or dd-MM-yyyy just to name two). This could be determined, but by the time you do all the stressing and parsing, you will still end up with some situation where there is an unexpected format used, and more tweaks will be be necessary.
You can also use some external program that will return a date slug in your preferred format, but that has disadvantages of needing to distribute the utility program with your script/batch.
There are also batch tricks using the CMOS clock in a pretty raw way, but that is tooo close to bare wires for most people, and also not always the preferred place to retrieve the date/time.
Below is a solution that avoids the above problems. Yes, it introduces some other issues, but for my purposes I found this to be the easiest, clearest, most portable solution for creating a datestamp in .bat files for modern Windows systems. This is just an example, but I think you will see how to modify for other date and/or time formats, etc.
Here is how I generate a log filename (based on http://ss64.com/nt/syntax-getdate.html):
This is my 2 cents for a
datetime string
. OnMM DD YYYY
systems switch the first and second%DATE:~
entries.I ended up with this script:
:: On WIN2008R2 e.g. I needed to make your 'set month=%date:~3,2%' like below ::otherwise 00 appears for MONTH