1

I have the following code

set x=%date /T %
date 16/12/2012
date 15/12/2012

some stuff goes here    
echo set your date

date %x%       <--- getting error in that line.
pause

So how can i get the date in the format dd/mm/yy

Dylan Corriveau
  • 2,565
  • 4
  • 27
  • 36
Arpit
  • 12,427
  • 2
  • 25
  • 40

9 Answers9

10

You can get the date format of dd/mm/yy by using wmic command. This command allows you to get current date without getting affected by regional settings.

    @echo off
    SETLOCAL EnableDelayedExpansion

    for /f "skip=1 tokens=1-6 delims= " %%a in ('wmic path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') do (
        IF NOT "%%~f"=="" (
            set /a FormattedDate=10000 * %%f + 100 * %%d + %%a
            set FormattedDate=!FormattedDate:~-2,2!/!FormattedDate:~-4,2!/!FormattedDate:~-6,2!
        )
    )

    echo %FormattedDate%
    PAUSE

You can save it as date.bat and run this batch file by executing the following in command prompt:

C:\>date.bat
21/01/13
Press any key to continue...

Hope this helps.

Dale
  • 1,825
  • 1
  • 15
  • 24
4

Two more ways that do not depend on the time settings (both taken from :How get data/time independent from localization:).And both also get the day of the week and none of them requires admin permissions!:

1.MAKECAB - will work on EVERY windows system (fast but creates a small temp file ) (the foxidrive script):

@echo off
pushd "%temp%"
makecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul >nul
for /f "tokens=3-7" %%a in ('find /i "makecab"^<~.rpt') do (
   set "current-date=%%e-%%b-%%c"
   set "current-time=%%d"
   set "weekday=%%a"
)
del ~.*
popd
echo %weekday% %current-date% %current-time%
pause

2. ROBOCOPY - it's not native command for windows xp and win 2003 but can be downloaded from microsoft site .But is built-in in everything from Vista and above:

 @echo off
setlocal 
for /f "skip=8 tokens=2,3,4,5,6,7,8 delims=: " %%D in ('robocopy /l * \ \ /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (
 set "dow=%%D"
 set "month=%%E"
 set "day=%%F"
 set "HH=%%G"
 set "MM=%%H"
 set "SS=%%I"
 set "year=%%J"
)

echo Day of the week: %dow%
echo Day of the month : %day%
echo Month : %month%
echo hour : %HH%
echo minutes : %MM%
echo seconds : %SS%
echo year : %year%
endlocal

And three more ways that uses other windows script languages.They will give you more flexibility e.g. you can get week of the year, time in milliseconds and so on.

3.JSCRIPT/BATCH hybrid (need to be saved as .bat).Jscript is available on every system form NT and above , as a part of windows script host (though can be disabled through the registry it's a rare case):

@if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment

@echo off
cscript //E:JScript //nologo "%~f0"
exit /b 0
*------------------------------------------------------------------------------*/

function GetCurrentDate() {
        // Today date time which will used to set as default date.
        var todayDate = new Date();
        todayDate = todayDate.getFullYear() + "-" +
                       ("0" + (todayDate.getMonth() + 1)).slice(-2) + "-" +
                       ("0" + todayDate.getDate()).slice(-2) + " " + ("0" + todayDate.getHours()).slice(-2) + ":" +
                       ("0" + todayDate.getMinutes()).slice(-2);

        return todayDate;
    }

WScript.Echo(GetCurrentDate()); 

4.VSCRIPT/BATCH hybrid (Is it possible to embed and execute VBScript within a batch file without using a temporary file?) same case as jscript , but hybridization is not so perfect:

:sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%\System32\doskey.exe %windir%\System32\'.exe >nul
'& echo current date:
'& cscript /nologo /E:vbscript "%~f0"
'& exit /b

'0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
'1 = vbLongDate - Returns date: weekday, monthname, year
'2 = vbShortDate - Returns date: mm/dd/yy
'3 = vbLongTime - Returns time: hh:mm:ss PM/AM
'4 = vbShortTime - Return time: hh:mm

WScript.echo  Replace(FormatDateTime(Date,1),", ","-") 

5.POWERSHELL - can be installed on every machine that has .net - download from Microsoft (v1 , v2 , v3 (only for win7 and above)).Installed by default on everything form Win7/Win2008 and above :

C:\>powershell get-date -format "{dd-MMM-yyyy HH:mm}"

6.Self-compiled jscript.net/batch (never seen a windows machine without .net so I think this is a pretty portable):

@if (@X)==(@Y) @end /****** silent line that start jscript comment ******

@echo off
::::::::::::::::::::::::::::::::::::
:::       compile the script    ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist "%~n0.exe" goto :skip_compilation

set "frm=%SystemRoot%\Microsoft.NET\Framework\"
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
    if exist "%%v\jsc.exe" (
        rem :: the javascript.net compiler
        set "jsc=%%~dpsnfxv\jsc.exe"
        goto :break_loop
    )
)
echo jsc.exe not found && exit /b 0
:break_loop


call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
:::       end of compilation    ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation

"%~n0.exe" 

exit /b 0


****** end of jscript comment ******/
import System;
import System.IO;

var dt=DateTime.Now;
 Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss"));

7.Logman This cannot get the year and day of the week.It's comparatively slow , also creates a temp file and is based on the time stamps that logman puts on its log files.Will work everything from XP and above.Probably will be never used by anybody - including me - but is one more way...

@echo off
setlocal
del /q /f %temp%\timestampfile_*

Logman.exe stop ts-CPU 1>nul 2>&1
Logman.exe delete ts-CPU 1>nul 2>&1

Logman.exe create counter ts-CPU  -sc 2 -v mmddhhmm -max 250 -c "\Processor(_Total)\%% Processor Time" -o %temp%\timestampfile_ >nul
Logman.exe start ts-CPU 1>nul 2>&1

Logman.exe stop ts-CPU >nul 2>&1
Logman.exe delete ts-CPU >nul 2>&1
for /f "tokens=2 delims=_." %%t in  ('dir /b %temp%\timestampfile_*^&del /q/f %temp%\timestampfile_*') do set timestamp=%%t

echo %timestamp%
echo MM: %timestamp:~0,2%
echo dd: %timestamp:~2,2%
echo hh: %timestamp:~4,2%
echo mm: %timestamp:~6,2%

endlocal
exit /b 0

more information about get-date function.

Community
  • 1
  • 1
npocmaka
  • 51,748
  • 17
  • 123
  • 166
1

This is tested on my system and it sets the date to required format. In case of error message of not "not enough required privileges or A required privilege is not held by the client" try running the script as Administrator. This should work fine then.

@echo off
set x=%DATE:~0,2%/%DATE:~3,2%/%DATE:~6,4%
echo %x%
set date=%x%
echo %date%
  • Not working! the date format dd/mm/-yy is not accepted. try removing set from set date,you get the error. – Arpit Jan 21 '13 at 15:42
  • This worked for me: `set x=%DATE:~4,2%/%DATE:~7,2%/%DATE:~10,4%` if the format is "Thu 03/03/2016" – Shai Alon Mar 03 '16 at 13:20
1

have you tried SET x=%date:~-10%, i know it works with windows 7.

colin lamarre
  • 1,581
  • 1
  • 16
  • 23
  • This helped me because some systems return the day of week while others didn't. This removed the day of the week. – coderboy Apr 01 '16 at 15:03
0

Your assignment set x=%date /T % is wrong. The percent signs expand variables, they don't provide command substitution functionality.

Windows already provides an automatic environment variable %DATE% with the current date (also a variable %TIME% with the current time), so you can simply do this:

set x=%DATE%
date 16/12/2012
date 15/12/2012

rem stuff

date %x%
pause
Ansgar Wiechers
  • 175,025
  • 22
  • 204
  • 278
  • try running the code! date 21-jan-13 The system cannot accept the date entered. – Arpit Jan 21 '13 at 15:44
  • Fix your date format. `date` can only process numeric values. – Ansgar Wiechers Jan 21 '13 at 17:31
  • this line "set x=%DATE%" gives x= 21-jan-13 – Arpit Jan 21 '13 at 17:33
  • That is because you defined that particular (short) date format in your computer's regional settings. Change that from `DD-MMM-YYYY` to `DD/MM/YYYY` (or `DD-MM-YYYY`) and the problem will vanish. – Ansgar Wiechers Jan 21 '13 at 17:38
  • Most systems I know use a numeric short date format. Anyway, you already got a solution that takes care of this issue. If you're not satisfied with it I'd recommend switching to a different script language. Batch is a rather bad choice when it comes to dealing with date or time values. – Ansgar Wiechers Jan 21 '13 at 17:55
  • agree with you! it is really nonsense to write that much code for just getting the date. i like bash scripts. but this time i don't have any choice. – Arpit Jan 21 '13 at 17:57
0

Dale's answer helped me a lot. I modified his solution to get the time in format hhmmdd:

@echo off
SETLOCAL EnableDelayedExpansion
rem Fill variables: %%a=Day %%b=Hour %%c=Minute %%d=Month %%e=Second %%f=Year
for /f "skip=1 tokens=1-6 delims= " %%a in ('wmic path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') do (
    IF NOT "%%~f"=="" (
    rem Adding leading zeros:
        set /a FormattedTime=1000000 + 10000 * %%b + 100 * %%c + %%e
    rem reading from the right to left: 
        set FormattedTime=!FormattedTime:~-6,2!!FormattedTime:~-4,2!!FormattedTime:~-2,2!
    )
)
echo %FormattedTime%
Ales
  • 1
  • for `hhmmss` (I think, `hhmmdd`is a typo) there is a much easyer way: `for /f %%i in ('wmic os get localdatetime^|find "."') do set x=%%i` and `echo %x:~8,6%` (including leading zeros) – Stephan Feb 11 '15 at 19:41
0

I know this is an old post, but I've found a way to do it without wmic:

At first, I've found a kind of answer and work with that:

You can try this ! This should work on windows machines.

for /F "usebackq tokens=1,2,3 delims=-" %%I IN (echo %date%) do echo "%%I" "%%J" "%%K" https://stackoverflow.com/a/14820126/3735825

Then I worked with this and did this one:

for /F "usebackq tokens=1,2,3,4 delims=/, " %%I IN (`echo %date%`) do ECHO %%L-%%K-%%J

It deletes the spaces and the separators from the %date% command and let you use any kind of part of the date as a variable; for example if I want to set the date as YYYYMMDD The code should be like this:

for /F "usebackq tokens=1,2,3,4 delims=/, " %%I IN (`echo %date%`) do ECHO %%L%%K%%J

If do you need the variables alone and you need to use them as you want, then you can play with the following variables:

%%I = Day of Week
%%J = Day
%%K = Month
%%L = Year

I hope it help anyone.

Community
  • 1
  • 1
Juan Medina
  • 521
  • 5
  • 12
  • 1. Problem was SETTING date, not GETTING it. 2. `wmic` has a big advantage: it is independent to local settings. For example `echo %date%` gives me `11.02.2015` – Stephan Feb 11 '15 at 19:09
  • Stephan, sorry I was having a problem getting it, but this is what i do for setting it: – Juan Medina Feb 12 '15 at 20:35
  • Stephan, sorry I was having a problem getting it, but this is what i do for GET: `for /F "usebackq tokens=1,2,3,4 delims=/, " %%I IN ('echo %date%') do SET yyyy=%%L || SET mm=%%K || SET dd=%%J` and for setting the date is: `date 09-15-11 (Like date mm-dd-yy)` – Juan Medina Feb 12 '15 at 20:40
  • Another problem with date is that it respects the format that has been set up by the user, so different machines give different formats (30-Aug-17, for example). Your post was still useful. Thanks – Neil Gatenby Aug 30 '17 at 09:39
0

The following code works for me:

set DATE_NOW=!date:~6,4!!date:~0,2!!date:~3,2!   
set TIME_NOW=!time:~0,2!!time:~3,2!!time:~6,2!   

echo %DATE_NOW%                                  
echo %TIME_NOW%                                  
0

In my case, I need a date in format YYYY-MM-DD, not in 2019-May-09. So I modify universal decision from npocmaka with make cab:

@echo off
pushd "%temp%"
makecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul >nul
for /f "tokens=3-7" %%a in ('find /i "makecab"^<~.rpt') do (
    set "current-year=%%e"
    set "current-month=%%b"
    set "current-day=%%c"
    set "current-time=%%d"
    set "weekday=%%a"
)
del ~.*
popd

CALL :CASE_%current-month% 
IF ERRORLEVEL 1 CALL :DEFAULT_CASE 

ECHO Done.
GOTO NEXT

:CASE_Jan
    set "current-month=01"
    GOTO END_CASE
:CASE_Feb
    set "current-month=02"
    GOTO END_CASE
:CASE_Mar
    set "current-month=03"
    GOTO END_CASE
:CASE_Apr
    set "current-month=04"
    GOTO END_CASE
:CASE_May
    set "current-month=05"
    GOTO END_CASE
:CASE_Jun
    set "current-month=06"
    GOTO END_CASE
:CASE_Jul
    set "current-month=07"
    GOTO END_CASE
:CASE_Aug
    set "current-month=08"
    GOTO END_CASE
:CASE_Sep
    set "current-month=09"
    GOTO END_CASE
:CASE_Oct
    set "current-month=10"
    GOTO END_CASE
:CASE_Nov
    set "current-month=11"
    GOTO END_CASE
:CASE_Dec
    set "current-month=12"
    GOTO END_CASE


:DEFAULT_CASE
  set "current-month=xx"
  echo "Month is not in the English language! Fix it!"  
  GOTO END_CASE
:END_CASE
  VER > NUL # reset ERRORLEVEL
  GOTO :EOF # return from CALL

:NEXT
echo %weekday% %current-year%-%current-month%-%current-day% %current-time%
pause

Tested on Windows XP SP3 and Server 2008 R2 SP1.