41

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.

Mossen
  • 1,105
  • 2
  • 11
  • 15
  • 1
    http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi – jwsample Aug 12 '10 at 23:12
  • 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_52 – Mossen Aug 12 '10 at 23:22

15 Answers15

47

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.

poke
  • 2,750
  • 5
  • 23
  • 36
  • 34
    This seems highly localization dependent. – BrainSlugs83 Sep 22 '11 at 20:53
  • 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% – Bomba Ps Feb 03 '21 at 09:02
35

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.

aschipfl
  • 28,946
  • 10
  • 45
  • 77
28

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.

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
Ashraf
  • 601
  • 5
  • 11
  • 1
    Very good, powerful syntax, thanks for sharing. In the case where I had to use it, it was the easiest and clearest solution. – Peter Elzinga Jul 20 '16 at 12:06
  • 7
    Nice, but locality dependent. – mattpm Sep 25 '16 at 01:56
  • 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... – Antônio Medeiros May 12 '17 at 12:26
  • 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`? – Antônio Medeiros May 12 '17 at 12:34
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.

Luciano
  • 2,263
  • 3
  • 27
  • 49
  • @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. – Luciano Mar 06 '16 at 13:22
  • I see. I am using @aschipfl's solution now. – Kurtibert Mar 06 '16 at 14:29
  • 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. – Ulysses Alves Oct 02 '17 at 14:42
  • it doesn't work for Italian language and date 01/10/2020 – Valix85 Oct 01 '20 at 13:45
  • @Valix85 what is the name of year variable in Italian? If isn't it "aa" or "yy" add it to `set year=%yy%%aa%`. – Luciano Oct 01 '20 at 15:43
  • @Luciano variable day is empty, year and moth works fine. – Valix85 Oct 02 '20 at 13:17
7

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.

Joey
  • 316,376
  • 76
  • 642
  • 652
  • 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? – Mossen Aug 13 '10 at 01:09
  • `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. – Joey Aug 13 '10 at 01:19
  • 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) – Michal Pokluda Jan 30 '19 at 12:55
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%
vitperov
  • 1,182
  • 15
  • 17
2

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

Jason
  • 857
  • 6
  • 18
2

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
Community
  • 1
  • 1
It Wasn't Me
  • 2,145
  • 3
  • 15
  • 22
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.

JeffJak
  • 1,838
  • 5
  • 25
  • 40
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
FifthAxiom
  • 101
  • 1
  • 5
  • +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!? – It Wasn't Me Oct 11 '19 at 20:12
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
Hayz
  • 98
  • 4
  • Please note that your first solution is language dependent. Outside of the USA the date order may be different to MM DD YYYY. – David Gausmann Mar 30 '21 at 12:57
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
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.

ASdeL
  • 141
  • 5
-2
powershell Set-Date -Da (Get-Date -Y 1980 -Mon 11 -Day 17)
STTR
  • 186
  • 7