Batch scripting in Windows is a powerful way to automate tasks, but working with dates and times can be surprisingly tricky. Often, you’ll need a date/time string that’s suitable for inclusion in filenames, such as for archiving or creating unique identifiers. The default date and time formats on Windows systems are often locale-dependent and not ideal for programmatic use. This tutorial will guide you through methods for reliably generating filename-friendly date and time strings within your batch scripts.
The Problem with Default Date/Time Formats
The %date%
and %time%
variables in batch scripts capture the system’s current date and time, respectively. However, the format of these variables is determined by the regional settings of the computer. This means the order of day, month, and year can vary (e.g., MM/DD/YYYY vs. DD/MM/YYYY), and the time format may include AM/PM indicators or use a 12-hour clock instead of a 24-hour clock. This inconsistency can lead to errors or unexpected behavior in your scripts.
Method 1: Parsing date
and time
with for
Loops
A common approach is to parse the output of the date
and time
commands using for
loops and token delimiters. This allows you to extract the individual components (year, month, day, hour, minute) and reassemble them in the desired order.
@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%
date /t
: This command outputs the current date in a short, locale-dependent format. The/t
switch suppresses the header information.time /t
: This command outputs the current time in a short, locale-dependent format. The/t
switch suppresses the header information.for /f "tokens=..."
: Thefor /f
loop parses the output of the command within the single quotes ('...'
).tokens=2-4
: Specifies that the loop should extract tokens 2, 3, and 4 from the output. These typically correspond to month, day, and year, respectively (but depend on the locale).delims=/
: Defines the delimiters used to separate the tokens. In this case, it uses the forward slash (/
) and space (set mydate=...
: Assigns the extracted and reordered date components to themydate
variable.set mytime=...
: Assigns the extracted time components to themytime
variable.
This method is relatively simple to understand, but it’s still susceptible to locale-dependent formatting issues. It’s important to test it thoroughly on different systems with different regional settings.
Method 2: Using WMIC to Retrieve ISO 8601 Date/Time
A more reliable approach is to use the Windows Management Instrumentation Command-line (WMIC) to retrieve the date and time in a standardized ISO 8601 format. This format is independent of regional settings and ensures consistency.
@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo %ldt%
wmic os get LocalDateTime /VALUE
: This command retrieves theLocalDateTime
property from theWin32_OperatingSystem
WMI class, formatted as a key-value pair.for /F "usebackq tokens=1,2 delims=="
: Thisfor
loop parses the output ofwmic
. Theusebackq
option allows the command to be enclosed in backticks (`).if '.%%i.'=='.LocalDateTime.'
: This conditional statement ensures that we only process the line containing theLocalDateTime
value.set ldt=%%j
: Assigns theLocalDateTime
value to theldt
variable.set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% ...
: This series ofset
commands extracts the year, month, day, hour, minute, and second from theldt
variable using string substring operations and reassembles them in the desired ISO 8601 format (YYYY-MM-DD HH:MM:SS).
This method is generally the most robust and reliable way to generate filename-friendly date and time strings in Windows batch scripts, as it’s independent of regional settings.
Best Practices
- Choose the Right Method: For maximum portability and consistency, use the WMIC method. If you’re certain about the target environment’s regional settings, parsing the output of
date
andtime
might be sufficient. - Test Thoroughly: Always test your scripts on different systems with different regional settings to ensure they function correctly.
- Consider Time Zones: If your script needs to handle dates and times across different time zones, you’ll need to incorporate time zone conversion logic. This is beyond the scope of this tutorial but is an important consideration for more complex applications.
- Avoid Reserved Characters: When creating filenames, avoid using reserved characters (e.g., , /, :, *, ?, ", <, >, |) that are not allowed in filenames. Replace these characters with safe alternatives if necessary.