How do I get the day month and year from a Windows cmd.exe script?
Asked Answered
E

15

50

How do I get the current day month and year from inside a Windows cmd script? I need to get each value into a separate variable.

Enrollee answered 12/8, 2010 at 22:49 Comment(2)
#203590Fourcycle
I don't understand how this is supposed to work. If I execute the script at the link and print the result, it just gives me Thu_08_12_2010_161902_52Enrollee
A
29

A variant of script that works locale-independently. Put it in a text file with .cmd extension and run.

::: Begin set date

for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (call :set_date %%i %%j %%k %%l)
goto :end_set_date

:set_date
if "%1:~0,1%" gtr "9" shift
for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo,^|date') do (set %%m=%1&set %%n=%2&set %%o=%3)
goto :eof

:end_set_date
::: End set date

echo day in 'DD' format is %dd%; month in 'MM' format is %mm%; year in 'YYYY' format is %yy%

The variables %dd%, %mm% and %yy% will keep the day('DD' format), the month('MM' format) and the year('YYYY' format) respectively.

Articular answered 13/8, 2010 at 9:18 Comment(5)
Haven't tested this, but I suspect it is also highly localization dependent.Agential
+1, I love this solution because it works for both Windows XP and Windows7 where 'date /t' is returned as '11/02/2011' and 'Wed 11/02/2011' respectively.Diffraction
It's not working for russian locale! Its (дд мм гг) instead of (dd mm yy)Traveler
Also not working for polish locale (rr stands for year instead of yy)Tisbee
Works Great for English regardless of settings!Allocution
G
50

To get the year, month, and day you can use the %date% environment variable and the :~ operator. %date% expands to something like Thu 08/12/2010 and :~ allows you to pick up specific characters out of a variable:

set year=%date:~10,4%
set month=%date:~4,2%
set day=%date:~7,2%
set filename=%year%_%month%_%day%

Use %time% in similar fashion to get what you need from the current time.

set /? will give you more information on using special operators with variables.

Grounder answered 13/8, 2010 at 1:31 Comment(3)
This seems highly localization dependent.Agential
Yes thats right, localisation dependent. btw. there is error in listing. In windows 7 [6.1.7601], the tilda operator for set command says that it extract substring from variable in following way :~begining_char,number_of_chars, thus if date is 2021-02-30 to get year it should be : set year=%date:~0,4%Jana
Got a wrong date, the filename shows "/14_02_/0" instead of "2013_09_14".Emileemilee
M
44

The following batch code returns the components of the current date in a locale-independent manner and stores day, month and year in the variables CurrDay, CurrMonth and CurrYear, respectively:

for /F "skip=1 delims=" %%F in ('
    wmic PATH Win32_LocalTime GET Day^,Month^,Year /FORMAT:TABLE
') do (
    for /F "tokens=1-3" %%L in ("%%F") do (
        set CurrDay=0%%L
        set CurrMonth=0%%M
        set CurrYear=%%N
    )
)
set CurrDay=%CurrDay:~-2%
set CurrMonth=%CurrMonth:~-2%
echo Current day  :  %CurrDay%
echo Current month:  %CurrMonth%
echo Current year :%CurrYear%

There are two nested for /F loops to work around an issue with the wmic command, whose output is in unicode format; using a single loop results in additional carriage-return characters which impacts proper variable expansion.

Since day and month may also consist of a single digit only, I prepended a leading zero 0 in the loop construct. Afterwards, the values are trimmed to always consist of two digits.

Mourant answered 28/10, 2015 at 21:53 Comment(9)
Works for me (Chinese). Thanks!Azov
Works for me (English), although they all do for me :PAllocution
Works for me (Portuguese/Brazil)Mixture
Works for me (Swedish)Grayson
wmic is an own process/program, not the command prompt on its own - at that point I could also execute anything else to get unlocalized information.Bigler
Yes, @AmigoJack, wmic is an external command; there is no internal one that provides locale-independent date/time information…Mourant
Works for German as wellCochise
Working for Spanish (BO) BoliviaFlem
Thanks, I slightly modified this to use setx and now have this scheduled as a daily task so the variables are always up to date: gist.github.com/zommuter/677589dc001755d0c74f09c573f68c35Skricki
A
29

A variant of script that works locale-independently. Put it in a text file with .cmd extension and run.

::: Begin set date

for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (call :set_date %%i %%j %%k %%l)
goto :end_set_date

:set_date
if "%1:~0,1%" gtr "9" shift
for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo,^|date') do (set %%m=%1&set %%n=%2&set %%o=%3)
goto :eof

:end_set_date
::: End set date

echo day in 'DD' format is %dd%; month in 'MM' format is %mm%; year in 'YYYY' format is %yy%

The variables %dd%, %mm% and %yy% will keep the day('DD' format), the month('MM' format) and the year('YYYY' format) respectively.

Articular answered 13/8, 2010 at 9:18 Comment(5)
Haven't tested this, but I suspect it is also highly localization dependent.Agential
+1, I love this solution because it works for both Windows XP and Windows7 where 'date /t' is returned as '11/02/2011' and 'Wed 11/02/2011' respectively.Diffraction
It's not working for russian locale! Its (дд мм гг) instead of (dd mm yy)Traveler
Also not working for polish locale (rr stands for year instead of yy)Tisbee
Works Great for English regardless of settings!Allocution
S
14
echo %Date:~7,2% gets current day

7 is starting position 2 number of digits to display

echo %Date:~7,2% gets current day

echo %Date:~4,2% gets current month

echo %Date:~10,4% gets current year
Sewell answered 8/11, 2014 at 11:17 Comment(4)
Very good, powerful syntax, thanks for sharing. In the case where I had to use it, it was the easiest and clearest solution.Kellby
Nice, but locality dependent.Desdee
If echo %Date% outputs a date as dd/mm/yyyy (like 12/05/2017), the above code works if changed to %Date:~0,2%, %Date:~3,2% and %Date:~6,4%. Thinking about how Windows was designed (or could be designed), locality independency seems something difficult to achieve with a simple piece of code. That is not a problem for Linux or Unixes in general, though...Futility
Another example of how Windows makes things difficult: if it is 9am, echo %time% returns me ` 9:29:34,67` (with a blank space), couldn't it be 09?Futility
S
9

LANGUAGE INDEPENDENCY:

The Andrei Coscodan solution is language dependent, so a way to try to fix it is to reserve all the tags for each field: year, month and day on target languages. Consider Portugese and English, after the parsing do a final set as:

set Year=%yy%%aa%
set Month=%mm%
set Day=%dd%

Look for the year setting, I used both tags from English and Portuguese, it worked for me in Brazil where we have these two languages as the most common in Windows instalations. I expect this will work also for some languages with Latin origin like as French, Spanish, and so on.

Well, the full script could be:

@echo off
setlocal enabledelayedexpansion

:: Extract date fields - language dependent
for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (
        set v1=%%i& set v2=%%j& set v3=%%k
        if "%%i:~0,1%%" gtr "9" (set v1=%%j& set v2=%%k& set v3=%%l)

        for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo.^|date') do (
            set %%m=!v1!& set %%n=!v2!& set %%o=!v3!
    )
)

:: Final set for language independency (English and Portuguese - maybe works for Spanish and French)
set year=%yy%%aa%
set month=%mm%
set day=%dd%


:: Testing
echo Year:[%year%] - month:[%month%] - day:[%day%]

endlocal
pause

I hope this helps someone that deal with diferent languages.

Sarnoff answered 20/2, 2012 at 1:41 Comment(6)
@kurtibert: In the second block "Final set for language independency" take a look in the year variable being set from yy (English), and aa (Portuguese, Spanish, ...). You may need to include variables from others languages to set year, month and day, their concatenation is the approach to language independency.Sarnoff
I see. I am using @aschipfl's solution now.Dustproof
Does this script use only one digit if the month is less than 10 and two digits only if the month is 10 or greater? I need to print the month this way, so that I don't have leading zeroes when the month has only one digit.Irregularity
it doesn't work for Italian language and date 01/10/2020Preliminary
@Preliminary what is the name of year variable in Italian? If isn't it "aa" or "yy" add it to set year=%yy%%aa%.Sarnoff
@Sarnoff variable day is empty, year and moth works fine.Preliminary
I
6

The only reliably way I know is to use VBScript to do the heavy work for you. There is no portable way of getting the current date in a usable format with a batch file alone. The following VBScript file

Wscript.Echo("set Year=" & DatePart("yyyy", Date))
Wscript.Echo("set Month=" & DatePart("m", Date))
Wscript.Echo("set Day=" & DatePart("d", Date))

and this batch snippet

for /f "delims=" %%x in ('cscript /nologo date.vbs') do %%x
echo %Year%-%Month%-%Day%

should work, though.

While you can get the current date in a batch file with either date /t or the %date% pseudo-variable, both follow the current locale in what they display. Which means you get the date in potentially any format and you have no way of parsing that.

Impregnable answered 13/8, 2010 at 0:17 Comment(3)
Alright...sounds good, but are these VBScript methods in scope in the cmd shell? Do I have to install a library and reference it in the script?Enrollee
cscript is the console interpreter for the Windows Script Host. It exists since Windows 98 in the default installation of any Windows (except maybe Server Core). However, if possible I tend to avoid VBScript since the WSH can be disabled via group policies. Something that cannot be done with batch files. But in this specific case it's just painful with pure batch.Impregnable
The only upgrade I needed is to have 2-digit format for month and day - use this: Right("0" & DatePart("m",Date), 2) instead just: DatePart("m", Date)Hardball
T
6

This variant works for all localizations:

@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    if "%%B" NEQ "" (
        SET /A FDATE=%%F*10000+%%D*100+%%A
    )
)
@echo on
echo date=%FDATE%
echo year=%FDATE:~2,2%
echo month=%FDATE:~4,2%
Traveler answered 6/7, 2017 at 12:54 Comment(0)
V
5

I have converted to using Powershell calls for this purpose in my scripts. It requires script execution permission and is by far the slowest option. However it is also localization independent, very easy to write and read, and it is much more feasible to perform adjustments to the date like addition/subtraction or get the last day of the month, etc.

Here is how to get the day, month, and year

for /f %%i in ('"powershell (Get-Date).ToString(\"dd\")"') do set day=%%i
for /f %%i in ('"powershell (Get-Date).ToString(\"MM\")"') do set month=%%i
for /f %%i in ('"powershell (Get-Date).ToString(\"yyyy\")"') do set year=%%i

Or, here is yesterday's date in yyyy-MM-dd format

for /f %%i in ('"powershell (Get-Date).AddDays(-1).ToString(\"yyyy-MM-dd\")"') do set yesterday=%%i

Day of the week

for /f %%d in ('"powershell (Get-Date).DayOfWeek"') do set DayOfWeek=%%d

Current time plus 15 minutes

for /f %%i in ('"powershell (Get-Date).AddMinutes(15).ToString(\"HH:mm\")"') do set time=%%i

Valparaiso answered 11/6, 2019 at 18:1 Comment(0)
M
3

For one line!


Try using for wmic OS Get localdatetime^|find "." in for /f without tokens and/or delims, this works in any language / region and also, no user settings interfere with the layout of the output.

  • In command line:
for /f %i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%i &echo= year: !_date:~0,4!&&echo=month:   !_date:~4,2!&echo=  day:   !_date:~6,2!"

  • In bat/cmd file:
for /f %%i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%%i &echo= year: !_date:~0,4!&&echo=month:   !_date:~4,2!&echo=  day:   !_date:~6,2!"

Results:


 year: 2019
month:   06
  day:   12

  • With Hour and Minute in bat/cmd file:
for /f %%i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%%i &echo=  year: !_date:~0,4!&&echo= month:   !_date:~4,2!&echo=   day:   !_date:~6,2!&echo=  hour:   !_date:~8,2!&echo=minute:   !_date:~10,2!"

  • With Hour and Minute in command line:
for /f %i in ('wmic OS Get localdatetime^|find "."')do @cmd/v/c "set _date=%i &echo=  year: !_date:~0,4!&&echo= month:   !_date:~4,2!&echo=   day:   !_date:~6,2!&echo=  hour:   !_date:~8,2!&echo=minute:   !_date:~10,2!"

Results:


  year: 2020
 month:   05
   day:   16
  hour:   00
minute:   46
Mixture answered 12/6, 2019 at 13:25 Comment(0)
D
2

I think that Andrei Coscodan answer is the best when you can't make many assumptions. But sometimes having a one-liner is nice if you can make some some assumptions. This solution assumes that 'date \t' will return one of two formats. On WindowsXP 'date /t 'returns "11/23/2011", but on Windows7 it returns "Wed 11/23/2011".

FOR /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set mm=%%a&set dd=%%b&set yyyy=%%c& (if "%%a:~0,1" gtr "9" set mm=%%b&setdd=%%c&set yyyy=%%d))
:: Test results
echo day in 'DD' format is '%dd%'; month in 'MM' format is '%mm%'; year in 'YYYY' format is '%yyyy%'

Thanks to Andrei Consodan answer to help me with this one-line solution.

Diffraction answered 3/11, 2011 at 16:42 Comment(0)
V
1

Extract Day, Month and Year

The highest voted function and the accepted one do NOT work locale-independently since the DATE command is subject to localization too. For example (the accepted one): In English you have YYYY for year and in Holland it is JJJJ. So this is a no-go. The following script takes the users' localization from the registry, which is locale-independent.

@echo off

::: Begin set date
setlocal EnableExtensions EnableDelayedExpansion

:: Determine short date format (independent from localization) from registry
for /f "skip=1 tokens=3-5 delims=- " %%L in ( '2^>nul reg query "HKCU\Control Panel\International" /v "sShortDate"' ) do ( 

    :: Since we can have multiple (short) date formats we only use the first char from the format in a new variable
    set "_L=%%L" && set "_L=!_L:~0,1!" && set "_M=%%M" && set "_M=!_M:~0,1!" && set "_N=%%N" && set "_N=!_N:~0,1!"

    :: Now assign the date values to the new vars
    for /f "tokens=2-4 delims=/-. " %%D in ( "%date%" ) do ( set "!_L!=%%D" && set "!_M!=%%E" && set "!_N!=%%F" )
)


:: Print the values as is
echo.
echo This is the original date string --^> %date%
echo These are the splitted values    --^> Day: %d%, Month:%m%, Year: %y%.
echo.

endlocal

Extract only the Year

For a script I wrote I wanted only to extract the year (locale-independent) so I came up with this oneliner as I couldn't find any solution. It uses the 'DATE' var, multiple delimiters and checks for a number greater than 31. That then will be the current year. It's low on resources in contrast to some of the other solutions.

@echo off

setlocal EnableExtensions

for /f " tokens=2-4 delims=-./ " %%D in ( "%date%" ) do ( if %%D gtr 31 ( set "_YEAR=%%D" ) else ( if %%E gtr 31 ( set "_YEAR=%%E" ) else ( if %%F gtr 31 ( set "_YEAR=%%F" ) ) ) )

echo And the year is... %_YEAR%.
echo.

endlocal
Valorievalorization answered 17/4, 2018 at 15:33 Comment(1)
+1, but: My query result: sShortDate REG_SZ yyyy-MM-dd, And the script result: This is the original date string --> 2019-10-11 in 1º line, the second result: These are the splitted values --> Day: , Month:11, Year: 10., so, the value DD here :Day: , have noting!?Mixture
S
1

You can use simple variable syntax, here is an example:

@echo off
set month=%date:~0,2%
set day=%date:~3,2%
set year=%date:~6,4%
echo The current month is %month%
echo The current day is %day%
echo The current year is %year%
pause >nul

Another option is the for command, again here is my example:

@echo off
for /f "delims=/ tokens=1-3" %%a in ("%date%") do (
set month=%%a
set day=%%b
set year=%%c
)
echo The current month is %month%
echo The current day is %day%
echo The current year is %year%
pause >nul
Sensate answered 21/3, 2019 at 16:37 Comment(2)
Please note that your first solution is language dependent. Outside of the USA the date order may be different to MM DD YYYY.Aarika
And so is the 2nd solution. Not everyone has / as date separatorTibbs
S
0

Based on the great answers above, I would like to add this variation as a one-liner that simply assigns the year to the %year% environment variable:

for /f "skip=1 tokens=2 delims==" %%y in ('wmic PATH Win32_LocalTime GET Year /value') do set year=%%y
Sugar answered 15/10, 2020 at 18:14 Comment(0)
W
0

To set the variable Day in a batch script just use

FOR /F %%F IN ('date.exe +%%d') DO SET Day=%%F

where date.exe is in the GnuWin32 package coreutils. Proceed analogously for month and year. This solution does not depend on localization. You can use UnxUtils instead of GnuWin32, as well as other alternatives. No setup required. Just copy date.exe where you need it.

Woody answered 21/4, 2021 at 20:8 Comment(0)
B
-3
powershell Set-Date -Da (Get-Date -Y 1980 -Mon 11 -Day 17)
Boaten answered 16/10, 2014 at 21:30 Comment(1)
Why are you using set-date?Valparaiso

© 2022 - 2024 — McMap. All rights reserved.