Adrianna Mayo
Adrianna Mayo

Reputation: 83

separate day month and year from a date batch file

when i do

echo %date%

i get output as

pet 28.06.2013

other dates

pon -> monday
tor -> tuesday 
sre -> wedneday 
cet -> thursday 
pet -> friday 
sob -> saturday 
ned -> sunday

I wrote following batch file to get the day month and time. but its not working. please help/

FOR /F "tokens=1-3 delims=." %%A IN ("%sample%") DO (
    SET day=%%A
    SET month=%%B
    SET year=%%C
)
echo %day%
echo %month%
echo %year%

output

pet 28
06
2013

I want the output as

28
06
2013

Upvotes: 2

Views: 11099

Answers (4)

Ken White
Ken White

Reputation: 125757

This will do it based on the local date on your computer. I'm using offsets based on my local computer date, which is Fri 06/28/2013 - you can adjust for yours as shown below):

Mine (in dateparse.bat):

@ECHO OFF
@ECHO.
@ECHO Date is %Date%
SET DayOfWeek=%Date:~0,3%
SET Day=%Date:~7,2%
SET Month=%Date:~4,2%
SET Year=%Date:~10,4%
SET Today=%Date:~10,4%-%Date:~4,2%-%Date:~7,2%
@ECHO Year is %Year%, Month is %Month%, Day is %Day%, DayOfWeek is %DayOfWeek% 
@ECHO Today is %Today%
@ECHO.

Output:

Output of dateparse.bat

Explanation (first two assignments, with the rest left to you) - note that the offset of the output is zero based, so the first character is index 0, the second is index 1, and so forth:

  • SET DayOfWeek= creates an environmental variable named DayOfWeek
  • %date% produces display of date on your system, like pet 28.06.2013
  • :~,3 takes a substring, starting at the first (index 0) of 3 characters (Fri)
  • SET Day= creates the Day environmental variable Day
  • :~7,2 takes a substring, starting at position 8 (index 7), of 2 characters (28)

Yours (untested - you may need to adjust):

SET DayOfWeek=%Date:%~0,3%
SET Day=%Date:~4,2%
SET Month=%Date:~7,2%
SET Year=%Date:~10,4%
ECHO %Year% %Month% %Day% %DayOfWeek% %Today%

Upvotes: 7

foxidrive
foxidrive

Reputation: 41307

For a reliable date stamp this uses WMIC in XP Pro and above.

@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set dt=%%a
set datestamp=%dt:~0,8%
set timestamp=%dt:~8,6%
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 stamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%
echo stamp: "%stamp%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"

pause

Upvotes: 0

David Ruhmann
David Ruhmann

Reputation: 11377

Add a space as a delimiter.

FOR /F "tokens=1-4 delims=. " %%A IN ("%sample%") DO (
    SET day=%%B
    SET month=%%C
    SET year=%%D
)
echo %day%
echo %month%
echo %year%

Upvotes: 2

Magoo
Magoo

Reputation: 80211

Use

"tokens=2-4delims=. "

Note the SPACE before the closing "

Upvotes: 4

Related Questions