user270488
user270488

Reputation: 59

Batch file command for creating a file's name as per the current date

Sorry to ask the below question command but I am stuck by its simplicity.

I need a windows batch file which creates a text file having the name of the today date, as per the computer date.

10th July 2014 >>> 10072014 >>> 10-07-2014.txt

Thanks for your help

Upvotes: 0

Views: 5118

Answers (2)

Abhishek Dutta
Abhishek Dutta

Reputation: 85

Following is a custom technique where it generates files with names as the date. It also contains some pre-typed data so that you can generate at the time of creation only and save your time from mundane activity.

I have set Y i.e year as 2020, M i.e month as 09 and day is auto-generated from the for loop from 1 to 31.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET PATH=D:\ABHISHEK_DUTTA\WORK\DAILY_LOGS\
SET Y=2020
SET M=09
FOR /L %%I IN (1,1,31) DO ( 
  IF %%I GTR 9 (SET "D=%%I") ELSE (SET "D=0%%I")  
  SET FNAME=%PATH%%Y%%M%!D!.txt
  (ECHO Notes for !D!-%M%-%Y%.
  ECHO Discussions 
  ECHO 1.  
  ECHO 2.  
  ECHO Remark) > !FNAME!
)

It checks whether I variable is greater than 9 otherwise concatenates 0.

In FNAME i.e. the filename is concatenated with which the file is to be created.

Upvotes: 0

UserUnknown
UserUnknown

Reputation: 172

The way I parse time in this sense varies. I adjust based on the server or workstation on which I'm placing the batch file. No, this isn't very portable in that sense but it's easy enough to adjust.

If your short-date format is mm/dd/yyyy the easy way is

SET DT=%date:/=-%
ECHO New File > %DT%.txt

This makes the "/" in the short date a "-", which is compatible with file names.

For most server applications I go the extra mile and break out the MM/DD, etc.:

SET DD=%date:~0,2%
SET MM=%date:~3,2%
SET YY=%date:~8,2%
SET YYYY=%date:~6,4%
SET DT=<your desired combo of month, day, year>
ECHO New File > %DT%.txt

At that point it's very easy for me and avoids using FOR loops that parse dates and times to work regardless of location or regional settings. Which is not important to me.

This is essentially what is in this link, provided also by foxidrive. SO has a number of options.

Upvotes: 1

Related Questions