When working with Windows scripts, it’s often necessary to date an output file or backup folder created from the script. One common challenge is that the `%DATE%` variable returns a value with slashes in, which cannot be used on its own. In this blog post, we will explore a method for formatting the date to the ISO standard YYYYMMDD format and how to use it in your scripts.
The `%DATE%` variable is a built-in Windows command that returns the current date and time. However, the output is in the format “MM/DD/YYYY HH:MM:SS”, which can be inconvenient when working with dates only. To overcome this limitation, you can use the `STRFTIME` function to format the date to the desired ISO standard YYYYMMDD format.
Here’s an example of how to use the `STRFTIME` function to format the current date to the YYYYMMDD format:
“`
@echo off
for /f “tokens=2 delims=” %%a in (‘strftime “%Y%m%d”‘) do (
echo(%%a)
)
“`
In this example, the `strftime` function is used to format the current date to the YYYYMMDD format. The `for /f` loop iterates over each token in the output of the `strftime` command, and the `echo` command is used to print each token.
To use this method in your scripts, you can simply replace the `%DATE%` variable with the formatted date. For example, if you want to create a dated folder or file, you can use the following code:
“`
@echo off
mkdir “backup_%%Y%%m%%d”
“`
In this example, the `mkdir` command is used to create a new folder with the name “backup_%%Y%%m%%d”. The `%%Y%%m%%d` syntax uses the formatted date returned by the `strftime` function to create a unique folder name for each day.
Another common use case for this method is when you need to backup files to a dated folder. You can use the following code to create a dated folder and copy the files to it:
“`
@echo off
mkdir “backup_%%Y%%m%%d”
xcopy /y “C:\files” “backup_%%Y%%m%%d\*”
“`
In this example, the `mkdir` command is used to create a new folder with the name “backup_%%Y%%m%%d”. The `xcopy` command is then used to copy all files from the “C:\files” directory to the dated folder. The `/y` option tells `xcopy` to preserve the file dates, so the backup will include the correct date for each file.
In conclusion, this method provides a simple and effective way to date an output file or backup folder created from a Windows script. By using the `STRFTIME` function to format the current date to the ISO standard YYYYMMDD format, you can easily create unique dated folders and files for each day. This technique is versatile and can be used in a variety of scenarios, making it an essential tool for any Windows scripting enthusiast.