Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format date in Windows 7 batch job

I'm trying to use the current date in a Windows 7 batch job. The batch job opens multiple files which have today's date appended to them. Example:

start \\\Directory_Name\Rpts\20130801\0000A060_FileName_20130801.pdf

start \\\Directory_Name\Rpts\20130801\0000P083_FileName_20130801.pdf

start \\\Directory_Name\Rpts\20130801\00007P12_FileName_20130801.pdf

If I run echo %date% I get: "Thu 08/01/2013"

I know I can run echo %date:/=% and get: "Thu 08012013*"

But I want to remove the "Thu" (today's day) and format the date to "20130801" (yyyymmdd) instead of mmddyyyy.

So eventually the open file command would look like the following with the correct %date% command inserted: start \\\Directory_Name\Rpts\%date%\00007P12_FileName_%date%.pdf

Anyone know how I can do this?

like image 413
user2234571 Avatar asked Aug 01 '13 22:08

user2234571


People also ask

How do I format a date in DOS?

If you provide a date in the format MM-DD-YY, the system date is set to that date. When specifying a two-digit year, the digits 00-99 correspond to the years 1980-2099. In modern versions of Windows, the date command accepts a four-digit date, e.g., MM-DD-YYYY.

How do I get the current date and time in CMD?

On a Microsoft Windows system, you can obtain the current date using the date /t command (the /t option prevents the command from prompting for a change to the the date) or by using echo %date% to display the contents of the date environment variable.

What is %% K in batch file?

So %%k refers to the value of the 3rd token, which is what is returned.


3 Answers

A robust, region insensitive method:

@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set "dt=%%a"
set "YYYY=%dt:~0,4%"
set "MM=%dt:~4,2%"
set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%"
set "Min=%dt:~10,2%"
set "Sec=%dt:~12,2%"

set datestamp=%YYYY%%MM%%DD%
set timestamp=%HH%%Min%%Sec%
set fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
like image 175
foxidrive Avatar answered Oct 01 '22 14:10

foxidrive


This is a bit simpler of a way of doing it with substrings:

set buildDate=%DATE:~4,10%
set dateStr=%buildDate:~6,4%%buildDate:~3,2%%buildDate:~0,2%
like image 37
Egg Avatar answered Oct 01 '22 14:10

Egg


Here is a solution, that is independent of local time format:

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I

and then %datetime:~0,8% will give you your YYYYMMDD

like image 38
Stephan Avatar answered Oct 01 '22 14:10

Stephan