Sofia
Sofia

Reputation: 1

How to store a date command to a Variable in CMD

Let's say I want to store the date in a variable and use the if statment to call the variable. This is what i did so far @echo off

FOR /F %F IN ('date.cmd') do date SET result=%F

IF  %result%== 11/14/2013(echo complete) ELSE
(echo failed)

Upvotes: 0

Views: 866

Answers (2)

Magoo
Magoo

Reputation: 80138

Why not simply use the inbuilt %date% variable?

Note that `%date% may contain the dayname and also the separator and sequence of elements may also vary between users.

Perhaps

for /f "tokens=1,2" %%a in ("%date%") do if "%%b"=="" (set result=%%a) else (set result=%%b)
echo result is %result%
IF %result%==11/14/2013 (echo complete) ELSE (echo failed)

would suit.

Upvotes: 1

foxidrive
foxidrive

Reputation: 41257

This code will give you reliable YY DD MM YYYY HH Min Sec variables in XP Pro and higher.

Parsing the date output gives you different results as it depends on the locale and also the user can change the date format.

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & 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 "result=%MM%/%DD%/%YYYY%"

IF "%result%"=="11/14/2013" (echo complete) ELSE (echo failed)
pause

Upvotes: 0

Related Questions