Safe way to get current day month and year in batch - windows

I am trying to write a batch script that will get the current day, month and year in a safe manner(i.e. independent of the date format). Unfortunately all the internet sources I have found propose something like:
SET CURRENT_DATE=%DATE: =0%
SET YEAR=%DATE:~-4%
SET MONTH=%DATE:~3,2%
SET DAY=%DATE:~5,2%
This will work if my date is in format yyyy/mm/dd or yyyy-mm-dd but will not if it is in format yy-mm-dd or some other format. Is there a safe way to get the year, month and day?
And one more question - is it possible to know what the day separator is(/ in the first case and - in the other cases).

The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in XP Pro and higher.
#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 "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
Here is a VBS solution:
:: date time using WSH/VBS
:: datetime.bat V4.2
::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: This uses Windows Scripting Host to set variables to
:: the current date/time/day/day_number/week_of_year etc
:: for Win9x/ME/NT/W2K/XP/Vista/Win7/Win8 etc
:: Thanks go to Todd Vargo for his scripting
::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#echo off
set TmpFile="%temp%.\tmp.vbs"
echo> %TmpFile% n=Now
echo>>%TmpFile% With WScript
echo>>%TmpFile% .Echo "set m1=" + monthname(month(n), true)
echo>>%TmpFile% .Echo "set m2=" + monthname(month(n), false)
echo>>%TmpFile% .Echo "set woy=" + CStr(datepart("ww", n))
echo>>%TmpFile% .Echo "set year=" + CStr(Year(n))
echo>>%TmpFile% .Echo "set yr=" + Right(Year(n),2)
echo>>%TmpFile% .Echo "set month="+ Right(100+Month(n),2)
echo>>%TmpFile% .Echo "set day=" + Right(100+Day(n),2)
echo>>%TmpFile% .Echo "set hour=" + Right(100+Hour(n),2)
echo>>%TmpFile% .Echo "set min=" + Right(100+Minute(n),2)
echo>>%TmpFile% .Echo "set sec=" + Right(100+Second(n),2)
echo>>%TmpFile% .Echo "set dow=" + WeekDayName(Weekday(n),1)
echo>>%TmpFile% .Echo "set dow2=" + WeekDayName(Weekday(n))
echo>>%TmpFile% .Echo "set iso=" + CStr(1 + Int(n-2) mod 7)
echo>>%TmpFile% .Echo "set iso2=" + CStr(Weekday(n,2))
echo>>%TmpFile% End With
cscript //nologo "%temp%.\tmp.vbs" > "%temp%.\tmp.bat"
call "%temp%.\tmp.bat"
del "%temp%.\tmp.bat"
del %TmpFile%
set TmpFile=
set stamp=%year%-%month%-%day%.%hour%_%min%_%sec%
if not "%~1"=="" goto :EOF
echo The year is "%year%" or "%yr%"
echo The month is "%month%" "%m1%" "%m2%"
echo The day is "%day%" "%dow%" "%dow2%"
echo.
echo ISO8601 Day-Of-Week number is "%iso%" and week of year is: "%woy%"
echo.
echo The time in hh:mm:ss is "%hour%:%min%:%sec%"
echo The hour is "%hour%"
echo The minute is "%min%"
echo The second is "%sec%"
echo.
echo The date and time stamp is "%stamp%"
echo.
echo date A yyyymmdd "%year%%month%%day%"
echo date B mmddyyyy "%month%%day%%year%"
echo date C ddmmyyyy "%day%%month%%year%"
echo date D yymmdd "%yr%%month%%day%"
echo date E mmddyy "%month%%day%%yr%"
echo date F ddmmyy "%day%%month%%yr%"
pause
:: datetime.bat
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

First, you could retrieve the current settings from the registry (somewhere).
The format and also the separators.
But it's easier to use wmic instead, it has always the same format, the only drawback is, that it's take a bit of time, each time you start it.
Modified sample from SO: Log Date/Time
#echo off
setlocal EnableDelayedExpansion
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
SET /A FTIME=%%B*10000+%%C*100+%%E
)
)
ECHO !FDATE! - !FTIME!

Extract Day, Month and Year (locale-independent)
I wouldn't use WMIC since it's very high on resources and takes awhile to complete, especially on slower computers. The following script takes the users' localization from the registry, which is locale-independent. As far as I know is is the only batch solution that works. Of course you can also use a call to a VBScript but for me that's off-topic.
#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

Related

date and time not saved in correct format while executing batch file [duplicate]

Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using date. See #npocmaka's https://stackoverflow.com/a/19799236/8479
What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?
I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, Code_2008-10-14_2257.zip. Is there any easy way I can do this, independent of the regional settings of the machine?
I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.
So far I've got this, which on my machine gives me Tue_10_14_2008_230050_91:
rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%
rem Now use the timestamp by in a new ZIP file name.
"d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code
I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.
I'm using Windows Server 2003 and Windows XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).
See Windows Batch File (.bat) to get current date in MMDDYYYY format:
#echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%
If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
C:> .\date.bat
2008-10-14_0642
If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:
#echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]
C:>test.cmd
Local date is [2012-06-19 10:23:47.048]
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!:
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
More information about get-date function.
ROBOCOPY - it's not native command for Windows XP and Windows Server 2003, but it can be downloaded from microsoft site. But is built-in in everything from Windows 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.
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());
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),", ","-")
PowerShell - can be installed on every machine that has .NET - download from Microsoft (v1, v2, v3 (only for Windows 7 and above)). It is installed by default on everything from Windows 7/Windows Server 2008 and above:
C:\> powershell get-date -format "{dd-MMM-yyyy HH:mm}"
To use it from a batch file:
for /f "delims=" %%# in ('powershell get-date -format "{dd-MMM-yyyy HH:mm}"') do #set _date=%%#
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"));
Logman This cannot get the year and day of the week. It's comparatively slow and also creates a temporary file and is based on the time stamps that logman puts on its log files. It will work on everything from Windows XP and above. It 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
One more way with WMIC which also gives week of the year and the day of the week, but not the milliseconds (for milliseconds check foxidrive's answer):
for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do #for /f %%# in ("%%#") do #set %%#
echo %day%
echo %DayOfWeek%
echo %hour%
echo %minute%
echo %month%
echo %quarter%
echo %second%
echo %weekinmonth%
echo %year%
Using TYPEPERF with some efforts to be fast and compatible with different language settings and as fast as possible:
#echo off
setlocal
:: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance
::if defined USERDOMAIN_roamingprofile (set "v=v4") else (set "v=")
for /f "tokens=4 delims=. " %%# in ('ver') do if %%# GTR 5 (set "v=v4") else ("v=")
set "mon="
for /f "skip=2 delims=," %%# in ('typeperf "\UDP%v%\*" -si 0 -sc 1') do (
if not defined mon (
for /f "tokens=1-7 delims=.:/ " %%a in (%%#) do (
set mon=%%a
set date=%%b
set year=%%c
set hour=%%d
set minute=%%e
set sec=%%f
set ms=%%g
)
)
)
echo %year%.%mon%.%date%
echo %hour%:%minute%:%sec%.%ms%
endlocal
MSHTA allows calling JavaScript methods similar to the JScript method demonstrated in #3 above. Bear in mind that JavaScript's Date object properties involving month values are numbered from 0 to 11, not 1 to 12. So a value of 9 means October.
<!-- : Batch portion
#echo off
setlocal
for /f "delims=" %%I in ('mshta "%~f0"') do set "now.%%~I"
rem Display all variables beginning with "now."
set now.
goto :EOF
end batch / begin HTA -->
<script>
resizeTo(0,0)
var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),
now = new Date(),
props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',
'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',
'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',
'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',
'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],
output = [];
for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}
close(fso.Write(output.join('\n')));
</script>
Regionally independent date time parsing
The output format of %DATE% and of the dir command is regionally dependent and thus neither robust nor smart. date.exe (part of UnxUtils) delivers any date and time information in any thinkable format. You may also extract the date/time information from any file with date.exe.
Examples: (in a cmd-script use %% instead of %)
date.exe +"%Y-%m-%d"
2009-12-22
date.exe +"%T"
18:55:03
date.exe +"%Y%m%d %H%M%S: Any text"
20091222 185503: Any text
date.exe +"Text: %y/%m/%d-any text-%H.%M"
Text: 09/12/22-any text-18.55
Command: date.exe +"%m-%d """%H %M %S """"
07-22 "18:55:03"`
The date/time information from a reference file:
date.exe -r c:\file.txt +"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S"
Using it in a CMD script to get year, month, day, time information:
for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n
Using it in a CMD script to get a timestamp in any required format:
for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe +"%%y-%%m-%%d %%H:%%M:%%S"') do set timestamp=%%i
Extracting the date/time information from any reference file.
for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n
Adding to a file its date/time information:
for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y-%%m-%%d.%%H%%M%%S"') do ren file.txt file.%%i.txt
date.exe is part of the free GNU tools which need no installation.
NOTE: Copying date.exe into any directory which is in the search path may cause other scripts to fail that use the Windows built-in date command.
Here's a variant from alt.msdos.batch.nt that works local-independently.
Put this in a text file, e.g. getDate.cmd
-----------8<------8<------------ snip -- snip ----------8<-------------
:: Works on any NT/2k machine independent of regional date settings
#ECHO off
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set '%%c'=%%k))
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
:EOF
-----------8<------8<------------ snip -- snip ----------8<-------------
To get the code to work sans error msg's to stderr, I had to add the single quotes arount the variable assignments for %%a, %%b and %%c. My locale (PT) was causing errors at one stage in the looping/parsing where stuff like "set =20" was getting executed. The quotes yield a token (albeit empty) for the left-hand side of the assignment statement.
The downside is the messy locale variable names: 'yy', 'mm' and 'dd'. But hey, who cares!
I use this (again not region independent (UK))
set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%
The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in Windows XP Professional and higher.
#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 "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
Unfortunately this is not immune to regional settings, but it does what you want.
set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%
Amazing the stuff you can find on Wikipedia.
Please use the following script to get the current day in the command line:
echo %Date:~0,3%day
"d:\Program Files\7-Zip\7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip
Another way (credit):
#For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do #(
Set Month=%%A
Set Day=%%B
Set Year=%%C
)
#echo DAY = %Day%
#echo Month = %Month%
#echo Year = %Year%
Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.
This isn't really briefer but might be a more flexible way (credit):
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%
Short answer :
:: Start - Run , type:
cmd /c "powershell get-date -format ^"{yyyy-MM-dd HH:mm:ss}^"|clip"
:: click into target media, Ctrl + V to paste the result
Long answer
#echo off
:: START USAGE ==================================================================
::SET THE NICETIME
:: SET NICETIME=BOO
:: CALL GetNiceTime.cmd
:: ECHO NICETIME IS %NICETIME%
:: echo nice time is %NICETIME%
:: END USAGE ==================================================================
echo set hhmmsss
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=:" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c
::DEBUG ECHO hhmmsss IS %hhmmsss%
::DEBUG PAUSE
echo %yyyymmdd%
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=." %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D
::DEBUG ECHO yyyymmdd IS %yyyymmdd%
::DEBUG PAUSE
set NICETIME=%yyyymmdd%_%hhmmsss%
::DEBUG echo THE NICETIME IS %NICETIME%
::DEBUG PAUSE
Here's a way to get date time in a single line:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %a in ('%date% %time%') do echo %c-%a-%b %d%e
In the US this will output "yyyy-mm-dd hhmm". Different regional settings will result in different %date% outputs, but you can modify the token order.
If you want a different format, modify the echo statement by rearranging the tokens or using different (or no) separators.
Just use this line:
PowerShell -Command "get-date"
Matthew Johnson's one-liner solution to get the one-liner date and time is eloquent and useful.
It does however need a simple modification to work from within a batch file:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e
And here is a similar batch-file for the time portion.
:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional time settings
::
:: Gets the time in ISO 8601 24-hour format
::
:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.
:: Since ISO 8601 does not care about AM/PM, we use %time%
::
#ECHO off
SETLOCAL ENABLEEXTENSIONS
for /f "tokens=1-4 delims=:,.-/ " %%i in ('echo %time%') do (
set 'hh'=%%i
set 'mm'=%%j
set 'ss'=%%k
set 'ff'=%%l)
ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%
ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]
set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%
echo %timestring%
:EOF
--jeroen
I changed the answer with the batch file from vMax so it works with the Dutch language too.
The Dutch - persistent as we are - have a few changes in the %date%, date/t, and date that break the original batch-file.
It would be nice if some people can check this against other Windows locales as well, and report back the results.
If the batch-file fails at your location, then please include the output of these two statements on the command prompt:
echo:^|date
date/t
This is a sample of the output you should get from the batch-file:
C:\temp>set-date-cmd.bat
Today is Year: [2011] Month: [01] Day: [03]
20110103
Here is the revised code with comments on why:
:: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by jeroen#pluimers.com for Dutch locale
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
:: set '%%c'=%%k
:: set 'yy'=%%k
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
:: if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
#ECHO off
set v_day=
set v_month=
set v_year=
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
::DEBUG echo toks=%toks%
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
if "%%a" GEQ "A" (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set 'yy'=%%k
)
)
)
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
set datestring=%V_Year%%V_Month%%V_Day%
echo %datestring%
:EOF
--jeroen
This is what I've used:
::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%
If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/
A function that is based on wmic:
:Now -- Gets the current date and time into separate variables
:: %~1: [out] Year
:: %~2: [out] Month
:: %~3: [out] Day
:: %~4: [out] Hour
:: %~5: [out] Minute
:: %~6: [out] Second
setlocal
for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t
endlocal & (
if "%~1" neq "" set %~1=%T:~0,4%
if "%~2" neq "" set %~2=%T:~4,2%
if "%~3" neq "" set %~3=%T:~6,2%
if "%~4" neq "" set %~4=%T:~8,2%
if "%~5" neq "" set %~5=%T:~10,2%
if "%~6" neq "" set %~6=%T:~12,2%
)
goto:eof
Upside: Region independent. Downside: Only system administrators can run wmic.exe.
Usage:
call:Now Y M D H N S
echo %Y%-%M%-%D% %H%:%N%:%S%
This echos a string like this:
2014-01-22 12:51:53
Note that function parameters are out-Parameters - that is, you must supply variable names instead of values.
All parameters are optional, so call:Now Y M is a valid call if you only want to get year and month.
I had a similar problem. I have an automatic daily download from an FTP server of an encrypted file. I wanted to decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and drop the decrypted file into a folder for the correct department.
I went through several suggestions for renaming the file according to date and was having no luck until I stumbled upon this simple solution.
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt
It worked perfectly (i.e., the filename comes out as "2011-06-14.txt").
(Source)
http://sourceforge.net/projects/unxutils/files/
Look inside the ZIP file for something called "Date.exe" and rename it "DateFormat.exe" (to avoid conflicts).
Put it in your Windows system32 folder.
It has a lot of "date output" options.
For help, use DateFormat.exe --h
I'm not sure how you would put its output into an environment variable... using SET.
Combine Powershell into a batch file and use the meta variables to assign each:
#echo off
for /f "tokens=1-6 delims=-" %%a in ('PowerShell -Command "& {Get-Date -format "yyyy-MM-dd-HH-mm-ss"}"') do (
echo year: %%a
echo month: %%b
echo day: %%c
echo hour: %%d
echo minute: %%e
echo second: %%f
)
You can also change the the format if you prefer name of the month MMM or MMMM and 12 hour to 24 hour formats hh or HH
Regional independent solution generating the ISO date format:
rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCU\Control Panel\International" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:
What could still be optimized:
Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated
:: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format
:: - Sets environment variables %_isotime% and %_now% to current time
:: - On failure, clears these environment variables
:: Inspired on -> https://ss64.com/nt/syntax-getdate.html
:: - (cX) 2017 adolfo.dimare#gmail.com
:: - http://stackoverflow.com/questions/203090
#echo off
set _isotime=
set _now=
:: Check that WMIC.exe is available
WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_
if not (%1)==() goto _help
SetLocal EnableDelayedExpansion
:: Use WMIC.exe to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF "%%~L"=="" goto _WMIC_done_
set _yyyy=%%L
set _mm=00%%J
set _dd=00%%G
set _hour=00%%H
set _minute=00%%I
set _second=00%%K
)
:_WMIC_done_
:: 1 2 3 4 5 6
:: %%G %%H %%I %%J %%K %%L
:: Day Hour Minute Month Second Year
:: 27 9 35 4 38 2017
:: Remove excess leading zeroes
set _mm=%_mm:~-2%
set _dd=%_dd:~-2%
set _hour=%_hour:~-2%
set _minute=%_minute:~-2%
set _second=%_second:~-2%
:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%
:: Set date/time in ISO 8601 format:
Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%
:: -> http://google.com/search?num=100&q=ISO+8601+format
if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am
if 1%_hour% LSS 112 goto _skip_12_
set /a _hour=1%_hour%-12
set _hour=%_hour:~-2%
set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm
:: -> https://ss64.com/nt/if.html
:: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows
:: 'if () else ()' will NOT set %_now% correctly !?
:_skip_12_
EndLocal & set _isotime=%_isotime% & set _now=%_now%
goto _out
:_WMIC_MISSING_
echo.
echo WMIC.exe command not available
echo - WMIC.exe needs Administrator privileges to run in Windows
echo - Usually the path to WMIC.exe is "%windir%\System32\wbem\WMIC.exe"
:_help
echo.
echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format
echo.
echo %%_now%% environment variable set to current date and time
echo %%_isotime%% environment variable to current time in ISO format
echo set _today=%%_isotime:~0,10%%
echo.
:_out
:: EOF: GetDate.cmd
I used date.exe, and renamed it to date_unxutils.exe to avoid conflicts.
Put it inside bin folder next to the batch script.
Code
:: Add binaries to temp path
IF EXIST bin SET PATH=%PATH%;bin
:: Create UTC Timestamp string in a custom format
:: Example: 20210128172058
set timestamp_command='date_unxutils.exe -u +"%%Y%%m%%d%%H%%M%%S"'
FOR /F %%i IN (%timestamp_command%) DO set timestamp=%%i
echo %timestamp%
Download UnxUtils
Link.
References
This awesome answer that I build upon.
PowerShell
Try the code below.
It will create the file or folder varible with the date as ddmmyyhhmm in 24hour time
[int] $day = Get-Date -UFormat %d
[int] $month = Get-Date -UFormat %m
[int] $year = Get-Date -UFormat %y
[String] $date = "$($day)$($month)$($year)"
$time = Get-Date -UFormat %R
$time -replace ‘[:]’,”"
$fileFolderName = $date + time
Given a known locality, for reference in functional form. The ECHOTIMESTAMP call shows how to get the timestamp into a variable (DTS in this example.)
#ECHO off
CALL :ECHOTIMESTAMP
GOTO END
:TIMESTAMP
SETLOCAL EnableDelayedExpansion
SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!
SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!
SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!
ENDLOCAL & SET "%~1=%DTS%"
GOTO :EOF
:ECHOTIMESTAMP
SETLOCAL
CALL :TIMESTAMP DTS
ECHO %DTS%
ENDLOCAL
GOTO :EOF
:END
EXIT /b 0
And saved to file, timestamp.bat, here's the output:
With Windows 7, this code works for me:
SET DATE=%date%
SET YEAR=%DATE:~0,4%
SET MONTH=%DATE:~5,2%
SET DAY=%DATE:~8,2%
ECHO %YEAR%
ECHO %MONTH%
ECHO %DAY%
SET DATE_FRM=%YEAR%-%MONTH%-%DAY%
ECHO %DATE_FRM%
I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.
:: Check your local date format
echo %date%
:: Output is Mon 08/15/2016
:: get day (start index, number of characters)
:: (index starts with zero)
set myday=%DATE:~0,4%
echo %myday%
:: output is Mon
:: get month
set mymonth=%DATE:~4,2%
echo %mymonth%
:: output is 08
:: get date
set mydate=%DATE:~7,2%
echo %mydate%
:: output is 15
:: get year
set myyear=%DATE:~10,4%
echo %myyear%
:: output is 2016
I note that the o/p did not ask for a region-independent solution. My solution is for the UK though.
This is the simplest possible solution, a 1-line solution, for use in a Batch file:
FOR /F "tokens=1-3 delims=/" %%A IN ("%date%") DO (SET today=%%C-%%B-%%A)
echo %today%
This solution can be varied, by altering the order of the variables %%A %%B and %%C in the output statement, to provide any date format desired (e.g. YY-MM-DD or DD-MM-YY).
My intention - my ONLY intention - in posting this answer is to demonstrate that this can be done on the command line, by using a single line of code to achieve it.
And that it is redundant to post answers running to 35 lines of code, as others have done, because the o/p specifically asked for a command line solution in the question. Therefore the o/p specifically sought a single-line solution.

get last month first date and last date in batch file

I am creating a batch file to execute some exe file. In that exe i need to specify first date(mm/dd/yyyy) and last day(mm/dd/yyyy) of last month.
#echo off
start "Testing" "c:\Program Files\app-cmd\bin\admincmd\imagelist -d 08/01/2015 -e 01/09/2015 > c:\test.txt"
Imagelist is an exe file where I need to pass value in -d and -e parameter.
I will add this script in schedule task so, it will run as schedule.
I can't use powershell as machine is win server 2003.
Please advise.
Assuming the date format on your system is MM/DD/YYYY as shown by date /t command:
#echo off
setlocal enableDelayedExpansion
for /f "delims=/ tokens=1,3" %%a in ("%date%") do set month=%%a& set year=%%b
if %month:~0,1%==0 set month=%month:~1%
set /a month-=1 && if !month!==0 set month=12&set /a year-=1
if not !month!==2 (
set /a last_day="31 - (month - 1) %% 7 %% 2"
) else (
set /a y4="year %% 4" & if !y4!==0 (
set /a y100="year %% 100" & if not !y100!==0 set is_leap_year=1
set /a y400="year %% 400" & if !y400!==0 set is_leap_year=1
)
if "!is_leap_year!"=="1" (set last_day=29) else set last_day=28
)
set month=0!month!
start "Testing" "c:\Program Files\app-cmd\bin\admincmd\imagelist" ^
-d !month:~-2!/01/!year! -e !month:~-2!/!last_day!/!year! > c:\test.txt
The code detects leap years as (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) for February and uses 31 - (month - 1) % 7 % 2 for other months.
You can try with
#echo off
setlocal enableextensions
call :getLastMonthLimits start end
echo %start% - %end%
goto :eof
:getLastMonthLimits startDateReturnVar endDateReturnVar
setlocal enableextensions disabledelayedexpansion
for %%t in ("%temp%\%~nx0.%random%%random%%random%.rpt") do (
for /f "tokens=4,7" %%a in ('
^>nul makecab /f nul /d RptFileName^="%%~ft" /V0
^& type "%%~ft" ^| find "MakeCAB Report:"
') do (
set /a "jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12"
set /a "m=(%%a+10) %% 12 + 1", "y=%%b-m/12", "d=30+((m+m/8) %% 2)", "m+=100"
if /i %%a==mar set /a "d=d-2 +(3-y %% 4)/3 -(99-y %% 100)/99 +(399-y %% 400)/399"
set /a "d+=100"
)
) & del "%%~ft"
endlocal & set "%~1=%m:~-2%/01/%y%" & set "%~2=%m:~-2%/%d:~-2%/%y%"
goto :eof
This uses a simplified version of the getDate function by carlos to get the date in a locale independent format (I prefer to use robocopy for it, but it is not a native tool in 2003). The rest are just arithmetic operations to calculate the month limits.
edited For the robocopy version (instead of the makecab to retrieve the date in locale independent format), just in case someone could need it
#echo off
call :getLastMonthLimits start end
echo %start% - %end%
goto :eof
:getLastMonthLimits startDateReturnVar endDateReturnVar
setlocal enableextensions disabledelayedexpansion
for /f "tokens=1-2 delims=/ " %%a in ('robocopy "|" . /njh ^| find "|"') do (
set /a "m=((1%%b-100)+10) %% 12 + 1", "y=%%a-m/12", "d=30+((m+m/8) %% 2)", "m+=100"
if %%b==03 set /a "d=d-2 +(3-y %% 4)/3 -(99-y %% 100)/99 +(399-y %% 400)/399"
set /a "d+=100"
)
endlocal & set "%~1=%m:~-2%/01/%y%" & set "%~2=%m:~-2%/%d:~-2%/%y%"
goto :eof

Windows console %DATE% Math

I would like to set the date in a Windows batch file to 7 days ago from today. I would like to do this in the following format.
set today=%date:~10,4%-%date:~4,2%-%date:~-7,2%
Any ideas how to subract the 7 day time delta here ?
I posted the description below in some site some time ago:
The following Batch files convert from Date to Julian Day Number an viceversa:
DATETOJULIAN.BAT:
#ECHO OFF
REM CONVERT DATE TO JULIAN DAY NUMBER
REM ANTONIO PEREZ AYALA
REM GET MONTH, DAY, YEAR VALUES
FOR /F "TOKENS=1-3 DELIMS=/" %%A IN ("%1") DO SET MM=%%A& SET DD=%%B& SET YY=%%C
REM ELIMINATE LEFT ZEROS
SET /A DD=10%DD% %% 100, MM=10%MM% %% 100
REM CALCULATE JULIAN DAY NUMBER
IF %MM% LSS 3 SET /A MM+=12, YY-=1
SET /A A=YY/100, B=A/4, C=2-A+B, E=36525*(YY+4716)/100, F=306*(MM+1)/10, JDN=C+DD+E+F-1524
JULIANTODATE.BAT:
REM CONVERT JULIAN DAY NUMBER TO MONTH, DAY, YEAR
REM ANTONIO PEREZ AYALA
SET /A W=(%1*100-186721625)/3652425, X=W/4, A=%1+1+W-X, B=A+1524, C=(B*100-12210)/36525, D=36525*C/100, E=(B-D)*10000/306001, F=306001*E/10000, DD=B-D-F, MM=E-1, YY=C-4716
IF %MM% GTR 12 SET /A MM-=12, YY+=1
REM INSERT LEFT ZEROS, IF NEEDED
IF %DD% LSS 10 SET DD=0%DD%
IF %MM% LSS 10 SET MM=0%MM%
REM SHOW THE DATE
ECHO %MM%/%DD%/%YY%
This way, to add/subtract a number of days to a date use the following lines:
CALL DATETOJULIAN %DATE%
SET /A NEWDATE=JDN+DAYS
CALL JULIANTODATE %NEWDATE%
Regards...
Reference: http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html
You just need to adjust your date format if it is not MM/DD/YYYY.
AdamEstrada asked about subtracting dates.
I had a tough time subtracting two Julian dates because of the SETLOCAL in the Julian functions. I did it by calling a function.
call:sub_Julians !Julian! %Today_Julian%
:sub_Julians
set /a delta_dates=%~1-%~2
...
goto:eof ::end:age_of_EPSdate
Ok, I needed a batch file to display the current JDAY for an DoD operations center. You can double-click the file and it will display in a CMD window. Then, press any key to exit.
Here's what I came up with:
#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%"
:: Call the day ordinal number subroutine
call :JDdayNumber %DD% %MM% %YYYY% DayOrdinalNumber
:: Display the result
echo.
echo Today is JDay %DayOrdinalNumber%
echo.
pause,
endlocal & goto :EOF
:: set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
:: set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
:: echo datestamp: "%datestamp%"
:: echo timestamp: "%timestamp%"
:: echo fullstamp: "%fullstamp%"
:: ============================================================
:: Subroutine: Calculate a day's ordinal number within the year
::JDdayNumber day month year return_
setlocal enableextensions enabledelayedexpansion
if %2 LEQ 2 (
set /a f=%1-1+31*^(%2-1^)
) else (
set /a a=%3
set /a b=!a!/4-!a!/100+!a!/400
set /a c=^(!a!-1^)/4-^(!a!-1^)/100+^(!a!-1^)/400
set /a s=!b!-!c!
set /a f=%1+^(153*^(%2-3^)+2^)/5+58+!s!
)
set /a return_=%f%+1
endlocal & set "%4=%return_%" & goto :EOF
I refactored the code of the JDate and GDate subroutines a little bit from http://www.robvanderwoude.com/datetimentmath.php.
Usage example:
Enter ISO date:
Enter number of days to add: 7
2017-01-01 + 7 days = 2017-01-08
Enter ISO date:
Enter number of days to add:
2017-01-08 + 7 days = 2017-01-15
Enter ISO date:
Enter number of days to add:
2017-01-15 + 7 days = 2017-01-22
Enter ISO date:
Enter number of days to add:
2017-01-22 + 7 days = 2017-01-29
Enter ISO date:
Enter number of days to add:
2017-01-29 + 7 days = 2017-02-05
Enter ISO date: 2017-02-12
Enter number of days to add: -7
2017-02-12 + -7 days = 2017-02-05
Code:
"Date math.bat":
#echo off
call :main %*
goto :eof
:main
setlocal
call :initialize "2017-01-01" "1"
endlocal
goto :eof
:initialize
setlocal
set "previousDate=%~1"
set /a "numberOfDays=%~2"
set /p "previousDate=Enter ISO date: "
set /p "numberOfDays=Enter number of days to add: "
set "currentDate="
call :addIsoDateDays "%previousDate%" "%numberOfDays%" currentDate
echo %previousDate% + %numberOfDays% days = %currentDate%
echo.
call :initialize "%currentDate%" "%numberOfDays%"
endlocal
goto :eof
:stripLeadingZero
setlocal
set "number=%~1"
if %number:~0,1% equ 0 (
set "number=%number:~1%"
)
(
endlocal
set "%~2=%number%"
)
goto :eof
:addLeadingZero
setlocal
set "number=%~1"
if %number% lss 10 (
set "number=0%number%"
)
(
endlocal
set "%~2=%number%"
)
goto :eof
:gregorianToJulianDate
setlocal
set "gregorianYear=%~1"
set "gregorianMonth=%~2"
set "gregorianDay=%~3"
call :stripLeadingZero "%gregorianMonth%" gregorianMonth
call :stripLeadingZero "%gregorianDay%" gregorianDay
set /a "julianYear=(%gregorianYear% + 4800)"
set /a "julianMonth=((%gregorianMonth% - 14) / 12)"
set /a "julianDate=((1461 * (%julianYear% + %julianMonth%) / 4) + (367 * (%gregorianMonth% - 2 - (12 * %julianMonth%)) / 12) - ((3 * ((%julianYear% + %julianMonth% + 100) / 100)) / 4) + (%gregorianDay% - 32075))"
(
endlocal
set "%~4=%julianDate%"
)
goto :eof
:isoToJulianDate
setlocal
set "date=%~1"
set "year="
set "month="
set "day="
for /f "tokens=1-3 delims=-" %%a in ("%date%") do (
set "year=%%a"
set "month=%%b"
set "day=%%c"
)
set /a "julianDate=0"
call :gregorianToJulianDate "%year%" "%month%" "%day%" julianDate
(
endlocal
set "%~2=%julianDate%"
)
goto :eof
:julianToGregorianDate
setlocal
set /a "julianDate=%~1"
set /a "p=(%julianDate% + 68569)"
set /a "q=(4 * %p% / 146097)"
set /a "r=(%p% - ((146097 * %q%) + 3) / 4)"
set /a "s=(4000 * (%r% + 1) / 1461001)"
set /a "t=(%r% - ((1461 * %s%) / 4) + 31)"
set /a "u=(80 * %t% / 2447)"
set /a "v=(%u% / 11)"
set /a "gregorianYear=((100 * (%q% - 49)) + %s% + %v%)"
set /a "gregorianMonth=(%u% + 2 - (12 * %v%))"
set /a "gregorianDay=(%t% - (2447 * %u% / 80))"
call :addLeadingZero "%gregorianMonth%" gregorianMonth
call :addLeadingZero "%gregorianDay%" gregorianDay
(
endlocal
set "%~2=%gregorianYear%"
set "%~3=%gregorianMonth%"
set "%~4=%gregorianDay%"
)
goto :eof
:julianToIsoDate
setlocal
set /a "julianDate=%~1"
set "year="
set "month="
set "day="
call :julianToGregorianDate "%julianDate%" year month day
set "isoDate=%year%-%month%-%day%"
(
endlocal
set "%~2=%isoDate%"
)
goto :eof
:addIsoDateDays
setlocal
set "previousIsoDate=%~1"
set /a "numberOfDays=%~2"
set /a "previousJulianDate=0"
call :isoToJulianDate "%previousIsoDate%" previousJulianDate
set /a "currentJulianDate=(%previousJulianDate% + %numberOfDays%)"
set "currentIsoDate="
call :julianToIsoDate "%currentJulianDate%" currentIsoDate
(
endlocal
set "%~3=%currentIsoDate%"
)
goto :eof
A simpler option is to call a PowerShell command from within your batch script to manipulate the date. The batch script can set the date as 7 days in the past with a single line.
powershell -command "((Get-date).AddDays(-7)).ToString('yyyy-MM-dd')">captureVar && set /p Today=<captureVar
The line starts out by instructing the cmd line to use PowerShell for the commands contained within the double quotes.
powershell -command "the powershell command(s)"
Next it used the PowerShell cmdlet Get-Date , and uses AddDays to change the date from the current value. A negative number will subtract and a positive number will add. The default format looks like
Friday, December 20, 2019 6:18:29 PM
To change the format you must change the date into a string with format instructions
.ToString('dddd MM/dd/yyyy HH:mm:ss.ffff K')
The output of the PowerShell command is redirected into a file named captureVar. Another option would have been to have PowerShell write it to a file.
powershell -command "((Get-date).AddDays(-7)).ToString('yyyy-MM-dd') | set-content 'captureVar'" && set /p Today=<captureVar
I used && to make it a one liner. But you can set the var anytime after value has been written to the file.
set /p Today=<captureVar
You should write in whatever scripting language you are most comfortable in. But remember that your options when writing a batch script isn't just batch commands. Windows has made it very easy to invoke PowerShell commands at anytime within your batch script. You can often find easy solutions to a given obstacle with PowerShell, insert that command into your script, then carry on as usual to finish your batch script.
A couple of things to remember when invoking PowerShell into your batch script:
Batch sees everything in double quotes as the PowerShell command. If you find a solution written in PowerShell that uses double quotes in the command, you must substitute those with single quotes. To escape characters, follow batch scripting rules. Batch variables can be read in the PowerShell command in the same way as batch (%var%). But values created in PowerShell must be redirected to be used later in your batch script. Any $var created in the PowerShell command is lost once the closing quote closes the PowerShell session.
There's an answer with calling powershell.
Though there are still machines running without powershell installed (at the moment of writing this XP,Vista,Windows7,Windows2003 and Windows2008 still have a descent OS share and are coming without installed powershell)
Other option will be using jscript within a bat script
Here's the dayAdder.bat that accepts only one argument - the days you want to add to the current date and prints the result:
#if (#X) == (#Y) #end /* JScript comment
#echo off
cscript //E:JScript //nologo "%~f0" %*
exit /b %errorlevel%
#if (#X)==(#Y) #end JScript comment */
var days=parseInt(WScript.Arguments.Item(0));
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
WScript.Echo(date.addDays(5));
WScript.Echo("Year: " + date.getFullYear());
WScript.Echo("Month: " + date.getMonth());
WScript.Echo("DayOfTeWEek: " + date.getDay());
usage and the output:
E:\scripts>call dayAdder.bat 7
Sun Nov 8 16:27:48 UTC+0200 2020
Year: 2020
Month: 10
DayOfTeWEek: 2
DayOfTheMonth: 3
You can modify it in way that will be suitable for you.

How to append a date in batch files

I have the following line in a batch file (that runs on an old Windows 2000 box):
7z a QuickBackup.zip *.backup
How do I append the date to the QuickBackup.zip file. So if I ran the batch file today, ideally, the file would be QuickBackup20090514.zip.
Is there a way to do this?
Bernhard's answer needed some tweaking work for me because the %DATE% environment variable is in a different format (as commented elsewhere). Also, there was a tilde (~) missing.
Instead of:
set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:0,2%
I had to use:
set backupFilename=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%
for the date format:
c:\Scripts>echo %DATE%
Thu 05/14/2009
#SETLOCAL ENABLEDELAYEDEXPANSION
#REM Use WMIC to retrieve date and time
#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 NOT "%%~F"=="" (
SET /A SortDate = 10000 * %%F + 100 * %%D + %%A
set YEAR=!SortDate:~0,4!
set MON=!SortDate:~4,2!
set DAY=!SortDate:~6,2!
#REM Add 1000000 so as to force a prepended 0 if hours less than 10
SET /A SortTime = 1000000 + 10000 * %%B + 100 * %%C + %%E
set HOUR=!SortTime:~1,2!
set MIN=!SortTime:~3,2!
set SEC=!SortTime:~5,2!
)
)
#echo on
#echo DATE=%DATE%, TIME=%TIME%
#echo HOUR=!HOUR! MIN=!MIN! SEC=!SEC!
#echo YR=!YEAR! MON=!MON! DAY=!DAY!
#echo DATECODE= '!YEAR!!MON!!DAY!!HOUR!!MIN!'
Output:
DATE=2015-05-20, TIME= 1:30:38.59
HOUR=01 MIN=30 SEC=38
YR=2015 MON=05 DAY=20
DATECODE= '201505200130'
This will work for the non-US date format (dd/MM/yyyy):
set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%
7z a QuickBackup%backupFilename%.zip *.backup
If you know your regional settings won't change you can do it as follows:
if your short date format is dd/MM/yyyy:
SET MYDATE=%DATE:~3,2%%DATE:~0,2%%DATE:~8,4%
if your short date format is MM/dd/yyyy:
SET MYDATE=%DATE:~0,2%%DATE:~3,2%%DATE:~8,4%
But there's no general way to do it that's independent of your regional settings.
I would not recommend relying on regional settings for anything that's going to be used in a production environment. Instead you should consider using another scripting language - PowerShell, VBScript, ...
For example, if you create a VBS file yyyymmdd.vbs in the same directory as your batch file with the following contents:
' yyyymmdd.vbs - outputs the current date in the format yyyymmdd
Function Pad(Value, PadCharacter, Length)
Pad = Right(String(Length,PadCharacter) & Value, Length)
End Function
Dim Today
Today = Date
WScript.Echo Pad(Year(Today), "0", 4) & Pad(Month(Today), "0", 2) & Pad(Day(Today), "0", 2)
then you will be able to call it from your batch file thus:
FOR /F %%i IN ('cscript "%~dp0yyyymmdd.vbs" //Nologo') do SET MYDATE=%%i
echo %MYDATE%
Of course there will eventually come a point where rewriting your batch file in a more powerful scripting language will make more sense than mixing it with VBScript in this way.
You can also access the date via the variable %DATE%
When testing my system %DATE% produces ddd dd/mm/yyyy
you can use substring operators to produce the format you desire
ie. running the following on MON 11/12/2018 with US regional settings
%DATE:~3,3% %DATE:~0,3% %DATE:~7,2%
Will produce an output:
11 Mon 12
the substring arguments are
%*variable*:~*startpos*,*numberofchars*%
This is all awkward and not local settings independent. Do it like this:
%CYGWIN_DIR%\bin\date +%%Y%%m%%d_%%H%%M% > date.txt
for /f "delims=" %%a in ('type "date.txt" 2^>NUL') do set datetime=%%a
echo %datetime%
del date.txt
Yes, use Cygwin date and all your problems are gone!
Sure.
FOR %%A IN (%Date:/=%) DO SET Today=%%A
7z a QuickBackup%TODAY%.zip *.backup
That is DDMMYYYY format.
Here's YYYYDDMM:
FOR %%A IN (%Date%) DO (
FOR /F "tokens=1-3 delims=/-" %%B in ("%%~A") DO (
SET Today=%%D%%B%%C
)
)
7z a QuickBackup%TODAY%.zip *.backup
There is a tech recipe available here that shows how to format it to MMDDYYYY, you should be able to adapt it for your needs.
echo on
#REM Seamonkey’s quick date batch (MMDDYYYY format)
#REM Setups %date variable
#REM First parses month, day, and year into mm , dd, yyyy formats and then combines to be MMDDYYYY
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%
echo %date%
EDIT: The reason did not work before was because of 'smartquotes' in the original text. I fixed them and the batch file will work if cut & pasted from this page.
I've used the environment variables technique covered here: http://cwashington.netreach.net/depo/view.asp?Index=19
http://cwashington.netreach.net/depo/default.asp?topic=repository&move=last&ScriptType=command&SubType=Misc
Here's the code from that site:
::~~Author~~. Brett Middleton
::~~Email_Address~~. brettm#arches.uga.edu
::~~Script_Type~~. nt command line batch
::~~Sub_Type~~. Misc
::~~Keywords~~. environment variables
::~~Comment~~.
::Sets or clears a group of environment variables containing components of the current date extracted from the string returned by the DATE /T command. These variables can be used to name files, control the flow of execution, etc.
::~~Script~~.
#echo off
::-----------------------------------------------------------------------------
:: SetEnvDate1.CMD 6/30/98
::-----------------------------------------------------------------------------
:: Description : Sets or clears a group of environment variables containing
:: : components of the current date extracted from the string
:: : returned by the DATE /T command. These variables can be
:: : used to name files, control the flow of execution, etc.
:: :
:: Requires : Windows NT with command extensions enabled
:: :
:: Tested : Yes, as demonstration
:: :
:: Contact : Brett Middleton <brettm#arches.uga.edu>
:: : Animal and Dairy Science Department
:: : University of Georgia, Athens
::-----------------------------------------------------------------------------
:: USAGE
::
:: SetEnvDate1 can be used as a model for coding date/time routines in
:: other scripts, or can be used by itself as a utility that is called
:: from other scripts.
::
:: Run or call SetEnvDate1 without arguments to set the date variables.
:: Variables are set for the day abbreviation (DT_DAY), month number (DT_MM),
:: day number (DT_DD) and four-digit year (DT_YYYY).
::
:: When the variables are no longer needed, clean up the environment by
:: calling the script again with the CLEAR argument. E.g.,
::
:: call SetEnvDate1 clear
::-----------------------------------------------------------------------------
:: NOTES
::
:: A time variable could be added by parsing the string returned by the
:: built-in TIME /T command. This is left as an exercise for the reader. B-)
::
:: This script illustrates the following NT command extensions:
::
:: 1. Use of the extended IF command to do case-insensitive comparisons.
::
:: 2. Use of the extended DATE command.
::
:: 3. Use of the extended FOR command to parse a string returned by a
:: command or program.
::
:: 4. Use of the "()" conditional processing symbols to group commands
:: for conditional execution. All commands between the parens will
:: be executed if the preceeding IF or FOR statement is TRUE.
::-----------------------------------------------------------------------------
if not "%1" == "?" goto chkarg
echo.
echo Sets or clears date/time variables in the command environment.
echo.
echo SetEnvDate1 [clear]
echo.
echo When called without arguments, the variables are created or updated.
echo When called with the CLEAR argument, the variables are deleted.
echo.
goto endit
::-----------------------------------------------------------------------------
:: Check arguments and select SET or CLEAR routine. Unrecognized arguments
:: are ignored and SET is assumed.
::-----------------------------------------------------------------------------
:chkarg
if /I "%1" == "CLEAR" goto clrvar
goto setvar
::-----------------------------------------------------------------------------
:: Set variables for the day abbreviation (DAY), month number (MM),
:: day number (DD) and 4-digit year (YYYY).
::-----------------------------------------------------------------------------
:setvar
for /F "tokens=1-4 delims=/ " %%i IN ('date /t') DO (
set DT_DAY=%%i
set DT_MM=%%j
set DT_DD=%%k
set DT_YYYY=%%l)
goto endit
::-----------------------------------------------------------------------------
:: Clear all variables from the environment.
::-----------------------------------------------------------------------------
:clrvar
for %%v in (DT_DAY DT_MM DT_DD DT_YYYY) do set %%v=
goto endit
:endit
As has been noted, parsing the date and time is only useful if you know the format being used by the current user (eg. MM/dd/yy or dd-MM-yyyy just to name 2). This could be determined, but by the time you do all the stressing and parsing, you will still end up with some situation where there is an unexpected format used, and more tweaks will be be necessary.
You can also use some external program that will return a date slug in your preferred format, but that has disadvantages of needing to distribute the utility program with your script/batch.
there are also batch tricks using the CMOS clock in a pretty raw way, but that is tooo close to bare wires for most people, and also not always the preferred place to retrieve the date/time.
Below is a solution that avoids the above problems. Yes, it introduces some other issues, but for my purposes I found this to be the easiest, clearest, most portable solution for creating a datestamp in .bat files for modern Windows systems. This is just an example, but I think you will see how to modify for other date and/or time formats, etc.
reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f
reg add "HKCU\Control Panel\International" /v sShortDate /d "yyMMdd" /f
#REM the following may be needed to be sure cache is clear before using the new setting
reg query "HKCU\Control Panel\International" /v sShortDate
set LogDate=%date%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f
Building on Joe's idea, here is a version which will build its own (.js) helper and supporting time as well:
#echo off
set _TMP=%TEMP%\_datetime.tmp
echo var date = new Date(), string, tmp;> "%_TMP%"
echo tmp = ^"000^" + date.getFullYear(); string = tmp.substr(tmp.length - 4);>> "%_TMP%"
echo tmp = ^"0^" + (date.getMonth() + 1); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo tmp = ^"0^" + date.getDate(); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo tmp = ^"0^" + date.getHours(); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo tmp = ^"0^" + date.getMinutes(); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo tmp = ^"0^" + date.getSeconds(); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo WScript.Echo(string);>> "%_TMP%"
for /f %%i in ('cscript //nologo /e:jscript "%_TMP%"') do set _DATETIME=%%i
del "%_TMP%"
echo YYYYMMDDhhmmss: %_DATETIME%
echo YYYY: %_DATETIME:~0,4%
echo YYYYMM: %_DATETIME:~0,6%
echo YYYYMMDD: %_DATETIME:~0,8%
echo hhmm: %_DATETIME:~8,4%
echo hhmmss: %_DATETIME:~8,6%
Sairam
With the samples given above, I have tried & came out with the script which I wanted. The position parameters mentioned in other example gave different results. I wanted to create one Batch file to take the Oracle data backup (export data) on daily basis, preserving distinct DMP files with date & time as part of file name. Here is the script which worked well:
cls
set dt=%date:~0,2%%date:~3,2%%date:~6,4%-%time:~0,2%%time:~3,2%
set fn=backup-%dt%.DMP
echo %fn%
pause A
exp user/password file=D:\DATA_DMP\%fn%
If you have WSL enabled (Windows 10 only) you can do it with bash in a locale neutral way.
set dateFile=%TEMP%\currentDate.txt
bash -c "date +%Y%m%d" > %dateFile%
set /p today=<%dateFile%
Feel free to replace the file redirection with a "for" loop abomination suggested in other answers here and over at Windows batch assign output of a program to a variable
I've found two ways that work regardless of the date settings.
On my pc, date/t returns
2009-05-27
You can either access the registry and read the regional settings
(HKEY_CURRENT_USER\Control Panel\International)
Or use a vbscript.
This is the ugly batch file/vbscript hybrid I created some time ago....
#Echo Off
set rnd=%Random%
set randfilename=x%rnd%.vbs
::create temp vbscript file
Echo Dim DayofWeek(7) > %temp%\%randfilename%
Echo DayofWeek(1)="Sun" >> %temp%\%randfilename%
Echo DayofWeek(2)="Mon" >> %temp%\%randfilename%
Echo DayofWeek(3)="Tue" >> %temp%\%randfilename%
Echo DayofWeek(4)="Wed" >> %temp%\%randfilename%
Echo DayofWeek(5)="Thu" >> %temp%\%randfilename%
Echo DayofWeek(6)="Fri" >> %temp%\%randfilename%
Echo DayofWeek(7)="Sat" >> %temp%\%randfilename%
Echo DayofWeek(0)=DayofWeek(Weekday(now)) >> %temp%\%randfilename%
Echo Mon=Left(MonthName(Month(now),1),3) >> %temp%\%randfilename%
Echo MonNumeric=right ( "00" ^& Month(now) , 2) >> %temp%\%randfilename%
Echo wscript.echo ( Year(Now) ^& " " ^& MonNumeric ^& " " ^& Mon ^& " " _ >> %temp%\%randfilename%
Echo ^& right("00" ^& Day(now),2) ^& " "^& dayofweek(0) ^& " "^& _ >> %temp%\%randfilename%
Echo right("00" ^& Hour(now),2)) _ >> %temp%\%randfilename%
Echo ^&":"^& Right("00" ^& Minute(now),2) ^&":"^& Right("00" ^& Second(Now),2) >> %temp%\%randfilename%
::set the output into vars
if "%1" == "" FOR /f "usebackq tokens=1,2,3,4,5,6" %%A in (`start /wait /b cscript //nologo %temp%\%randfilename%`) do Set Y2KYear=%%A& Set MonthNumeric=%%B& Set Month=%%C& Set Day=%%D& Set DayofWeek=%%E& Set Time=%%F
set year=%y2kyear:~2,2%
::cleanup
del %temp%\%randfilename%
It's not pretty, but it works.

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using date. See #npocmaka's https://stackoverflow.com/a/19799236/8479
What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?
I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, Code_2008-10-14_2257.zip. Is there any easy way I can do this, independent of the regional settings of the machine?
I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.
So far I've got this, which on my machine gives me Tue_10_14_2008_230050_91:
rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%
rem Now use the timestamp by in a new ZIP file name.
"d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code
I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.
I'm using Windows Server 2003 and Windows XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).
See Windows Batch File (.bat) to get current date in MMDDYYYY format:
#echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%
If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
C:> .\date.bat
2008-10-14_0642
If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:
#echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]
C:>test.cmd
Local date is [2012-06-19 10:23:47.048]
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!:
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
More information about get-date function.
ROBOCOPY - it's not native command for Windows XP and Windows Server 2003, but it can be downloaded from microsoft site. But is built-in in everything from Windows 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.
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());
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),", ","-")
PowerShell - can be installed on every machine that has .NET - download from Microsoft (v1, v2, v3 (only for Windows 7 and above)). It is installed by default on everything from Windows 7/Windows Server 2008 and above:
C:\> powershell get-date -format "{dd-MMM-yyyy HH:mm}"
To use it from a batch file:
for /f "delims=" %%# in ('powershell get-date -format "{dd-MMM-yyyy HH:mm}"') do #set _date=%%#
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"));
Logman This cannot get the year and day of the week. It's comparatively slow and also creates a temporary file and is based on the time stamps that logman puts on its log files. It will work on everything from Windows XP and above. It 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
One more way with WMIC which also gives week of the year and the day of the week, but not the milliseconds (for milliseconds check foxidrive's answer):
for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do #for /f %%# in ("%%#") do #set %%#
echo %day%
echo %DayOfWeek%
echo %hour%
echo %minute%
echo %month%
echo %quarter%
echo %second%
echo %weekinmonth%
echo %year%
Using TYPEPERF with some efforts to be fast and compatible with different language settings and as fast as possible:
#echo off
setlocal
:: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance
::if defined USERDOMAIN_roamingprofile (set "v=v4") else (set "v=")
for /f "tokens=4 delims=. " %%# in ('ver') do if %%# GTR 5 (set "v=v4") else ("v=")
set "mon="
for /f "skip=2 delims=," %%# in ('typeperf "\UDP%v%\*" -si 0 -sc 1') do (
if not defined mon (
for /f "tokens=1-7 delims=.:/ " %%a in (%%#) do (
set mon=%%a
set date=%%b
set year=%%c
set hour=%%d
set minute=%%e
set sec=%%f
set ms=%%g
)
)
)
echo %year%.%mon%.%date%
echo %hour%:%minute%:%sec%.%ms%
endlocal
MSHTA allows calling JavaScript methods similar to the JScript method demonstrated in #3 above. Bear in mind that JavaScript's Date object properties involving month values are numbered from 0 to 11, not 1 to 12. So a value of 9 means October.
<!-- : Batch portion
#echo off
setlocal
for /f "delims=" %%I in ('mshta "%~f0"') do set "now.%%~I"
rem Display all variables beginning with "now."
set now.
goto :EOF
end batch / begin HTA -->
<script>
resizeTo(0,0)
var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),
now = new Date(),
props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',
'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',
'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',
'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',
'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],
output = [];
for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}
close(fso.Write(output.join('\n')));
</script>
Regionally independent date time parsing
The output format of %DATE% and of the dir command is regionally dependent and thus neither robust nor smart. date.exe (part of UnxUtils) delivers any date and time information in any thinkable format. You may also extract the date/time information from any file with date.exe.
Examples: (in a cmd-script use %% instead of %)
date.exe +"%Y-%m-%d"
2009-12-22
date.exe +"%T"
18:55:03
date.exe +"%Y%m%d %H%M%S: Any text"
20091222 185503: Any text
date.exe +"Text: %y/%m/%d-any text-%H.%M"
Text: 09/12/22-any text-18.55
Command: date.exe +"%m-%d """%H %M %S """"
07-22 "18:55:03"`
The date/time information from a reference file:
date.exe -r c:\file.txt +"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S"
Using it in a CMD script to get year, month, day, time information:
for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n
Using it in a CMD script to get a timestamp in any required format:
for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe +"%%y-%%m-%%d %%H:%%M:%%S"') do set timestamp=%%i
Extracting the date/time information from any reference file.
for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n
Adding to a file its date/time information:
for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y-%%m-%%d.%%H%%M%%S"') do ren file.txt file.%%i.txt
date.exe is part of the free GNU tools which need no installation.
NOTE: Copying date.exe into any directory which is in the search path may cause other scripts to fail that use the Windows built-in date command.
Here's a variant from alt.msdos.batch.nt that works local-independently.
Put this in a text file, e.g. getDate.cmd
-----------8<------8<------------ snip -- snip ----------8<-------------
:: Works on any NT/2k machine independent of regional date settings
#ECHO off
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set '%%c'=%%k))
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
:EOF
-----------8<------8<------------ snip -- snip ----------8<-------------
To get the code to work sans error msg's to stderr, I had to add the single quotes arount the variable assignments for %%a, %%b and %%c. My locale (PT) was causing errors at one stage in the looping/parsing where stuff like "set =20" was getting executed. The quotes yield a token (albeit empty) for the left-hand side of the assignment statement.
The downside is the messy locale variable names: 'yy', 'mm' and 'dd'. But hey, who cares!
I use this (again not region independent (UK))
set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%
The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in Windows XP Professional and higher.
#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 "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
Unfortunately this is not immune to regional settings, but it does what you want.
set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%
Amazing the stuff you can find on Wikipedia.
Please use the following script to get the current day in the command line:
echo %Date:~0,3%day
"d:\Program Files\7-Zip\7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip
Another way (credit):
#For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do #(
Set Month=%%A
Set Day=%%B
Set Year=%%C
)
#echo DAY = %Day%
#echo Month = %Month%
#echo Year = %Year%
Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.
This isn't really briefer but might be a more flexible way (credit):
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%
Short answer :
:: Start - Run , type:
cmd /c "powershell get-date -format ^"{yyyy-MM-dd HH:mm:ss}^"|clip"
:: click into target media, Ctrl + V to paste the result
Long answer
#echo off
:: START USAGE ==================================================================
::SET THE NICETIME
:: SET NICETIME=BOO
:: CALL GetNiceTime.cmd
:: ECHO NICETIME IS %NICETIME%
:: echo nice time is %NICETIME%
:: END USAGE ==================================================================
echo set hhmmsss
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=:" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c
::DEBUG ECHO hhmmsss IS %hhmmsss%
::DEBUG PAUSE
echo %yyyymmdd%
:: this is Regional settings dependant so tweak this according your current settings
for /f "tokens=1-3 delims=." %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D
::DEBUG ECHO yyyymmdd IS %yyyymmdd%
::DEBUG PAUSE
set NICETIME=%yyyymmdd%_%hhmmsss%
::DEBUG echo THE NICETIME IS %NICETIME%
::DEBUG PAUSE
Here's a way to get date time in a single line:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %a in ('%date% %time%') do echo %c-%a-%b %d%e
In the US this will output "yyyy-mm-dd hhmm". Different regional settings will result in different %date% outputs, but you can modify the token order.
If you want a different format, modify the echo statement by rearranging the tokens or using different (or no) separators.
Just use this line:
PowerShell -Command "get-date"
Matthew Johnson's one-liner solution to get the one-liner date and time is eloquent and useful.
It does however need a simple modification to work from within a batch file:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e
And here is a similar batch-file for the time portion.
:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional time settings
::
:: Gets the time in ISO 8601 24-hour format
::
:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.
:: Since ISO 8601 does not care about AM/PM, we use %time%
::
#ECHO off
SETLOCAL ENABLEEXTENSIONS
for /f "tokens=1-4 delims=:,.-/ " %%i in ('echo %time%') do (
set 'hh'=%%i
set 'mm'=%%j
set 'ss'=%%k
set 'ff'=%%l)
ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%
ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]
set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%
echo %timestring%
:EOF
--jeroen
I changed the answer with the batch file from vMax so it works with the Dutch language too.
The Dutch - persistent as we are - have a few changes in the %date%, date/t, and date that break the original batch-file.
It would be nice if some people can check this against other Windows locales as well, and report back the results.
If the batch-file fails at your location, then please include the output of these two statements on the command prompt:
echo:^|date
date/t
This is a sample of the output you should get from the batch-file:
C:\temp>set-date-cmd.bat
Today is Year: [2011] Month: [01] Day: [03]
20110103
Here is the revised code with comments on why:
:: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by jeroen#pluimers.com for Dutch locale
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
:: set '%%c'=%%k
:: set 'yy'=%%k
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
:: if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
#ECHO off
set v_day=
set v_month=
set v_year=
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
::DEBUG echo toks=%toks%
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
if "%%a" GEQ "A" (
for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
set '%%a'=%%i
set '%%b'=%%j
set 'yy'=%%k
)
)
)
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%
ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
set datestring=%V_Year%%V_Month%%V_Day%
echo %datestring%
:EOF
--jeroen
This is what I've used:
::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%
If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/
A function that is based on wmic:
:Now -- Gets the current date and time into separate variables
:: %~1: [out] Year
:: %~2: [out] Month
:: %~3: [out] Day
:: %~4: [out] Hour
:: %~5: [out] Minute
:: %~6: [out] Second
setlocal
for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t
endlocal & (
if "%~1" neq "" set %~1=%T:~0,4%
if "%~2" neq "" set %~2=%T:~4,2%
if "%~3" neq "" set %~3=%T:~6,2%
if "%~4" neq "" set %~4=%T:~8,2%
if "%~5" neq "" set %~5=%T:~10,2%
if "%~6" neq "" set %~6=%T:~12,2%
)
goto:eof
Upside: Region independent. Downside: Only system administrators can run wmic.exe.
Usage:
call:Now Y M D H N S
echo %Y%-%M%-%D% %H%:%N%:%S%
This echos a string like this:
2014-01-22 12:51:53
Note that function parameters are out-Parameters - that is, you must supply variable names instead of values.
All parameters are optional, so call:Now Y M is a valid call if you only want to get year and month.
I had a similar problem. I have an automatic daily download from an FTP server of an encrypted file. I wanted to decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and drop the decrypted file into a folder for the correct department.
I went through several suggestions for renaming the file according to date and was having no luck until I stumbled upon this simple solution.
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt
It worked perfectly (i.e., the filename comes out as "2011-06-14.txt").
(Source)
http://sourceforge.net/projects/unxutils/files/
Look inside the ZIP file for something called "Date.exe" and rename it "DateFormat.exe" (to avoid conflicts).
Put it in your Windows system32 folder.
It has a lot of "date output" options.
For help, use DateFormat.exe --h
I'm not sure how you would put its output into an environment variable... using SET.
Combine Powershell into a batch file and use the meta variables to assign each:
#echo off
for /f "tokens=1-6 delims=-" %%a in ('PowerShell -Command "& {Get-Date -format "yyyy-MM-dd-HH-mm-ss"}"') do (
echo year: %%a
echo month: %%b
echo day: %%c
echo hour: %%d
echo minute: %%e
echo second: %%f
)
You can also change the the format if you prefer name of the month MMM or MMMM and 12 hour to 24 hour formats hh or HH
Regional independent solution generating the ISO date format:
rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCU\Control Panel\International" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:
What could still be optimized:
Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated
:: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format
:: - Sets environment variables %_isotime% and %_now% to current time
:: - On failure, clears these environment variables
:: Inspired on -> https://ss64.com/nt/syntax-getdate.html
:: - (cX) 2017 adolfo.dimare#gmail.com
:: - http://stackoverflow.com/questions/203090
#echo off
set _isotime=
set _now=
:: Check that WMIC.exe is available
WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_
if not (%1)==() goto _help
SetLocal EnableDelayedExpansion
:: Use WMIC.exe to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF "%%~L"=="" goto _WMIC_done_
set _yyyy=%%L
set _mm=00%%J
set _dd=00%%G
set _hour=00%%H
set _minute=00%%I
set _second=00%%K
)
:_WMIC_done_
:: 1 2 3 4 5 6
:: %%G %%H %%I %%J %%K %%L
:: Day Hour Minute Month Second Year
:: 27 9 35 4 38 2017
:: Remove excess leading zeroes
set _mm=%_mm:~-2%
set _dd=%_dd:~-2%
set _hour=%_hour:~-2%
set _minute=%_minute:~-2%
set _second=%_second:~-2%
:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%
:: Set date/time in ISO 8601 format:
Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%
:: -> http://google.com/search?num=100&q=ISO+8601+format
if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am
if 1%_hour% LSS 112 goto _skip_12_
set /a _hour=1%_hour%-12
set _hour=%_hour:~-2%
set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm
:: -> https://ss64.com/nt/if.html
:: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows
:: 'if () else ()' will NOT set %_now% correctly !?
:_skip_12_
EndLocal & set _isotime=%_isotime% & set _now=%_now%
goto _out
:_WMIC_MISSING_
echo.
echo WMIC.exe command not available
echo - WMIC.exe needs Administrator privileges to run in Windows
echo - Usually the path to WMIC.exe is "%windir%\System32\wbem\WMIC.exe"
:_help
echo.
echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format
echo.
echo %%_now%% environment variable set to current date and time
echo %%_isotime%% environment variable to current time in ISO format
echo set _today=%%_isotime:~0,10%%
echo.
:_out
:: EOF: GetDate.cmd
I used date.exe, and renamed it to date_unxutils.exe to avoid conflicts.
Put it inside bin folder next to the batch script.
Code
:: Add binaries to temp path
IF EXIST bin SET PATH=%PATH%;bin
:: Create UTC Timestamp string in a custom format
:: Example: 20210128172058
set timestamp_command='date_unxutils.exe -u +"%%Y%%m%%d%%H%%M%%S"'
FOR /F %%i IN (%timestamp_command%) DO set timestamp=%%i
echo %timestamp%
Download UnxUtils
Link.
References
This awesome answer that I build upon.
PowerShell
Try the code below.
It will create the file or folder varible with the date as ddmmyyhhmm in 24hour time
[int] $day = Get-Date -UFormat %d
[int] $month = Get-Date -UFormat %m
[int] $year = Get-Date -UFormat %y
[String] $date = "$($day)$($month)$($year)"
$time = Get-Date -UFormat %R
$time -replace ‘[:]’,”"
$fileFolderName = $date + time
Given a known locality, for reference in functional form. The ECHOTIMESTAMP call shows how to get the timestamp into a variable (DTS in this example.)
#ECHO off
CALL :ECHOTIMESTAMP
GOTO END
:TIMESTAMP
SETLOCAL EnableDelayedExpansion
SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!
SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!
SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!
ENDLOCAL & SET "%~1=%DTS%"
GOTO :EOF
:ECHOTIMESTAMP
SETLOCAL
CALL :TIMESTAMP DTS
ECHO %DTS%
ENDLOCAL
GOTO :EOF
:END
EXIT /b 0
And saved to file, timestamp.bat, here's the output:
With Windows 7, this code works for me:
SET DATE=%date%
SET YEAR=%DATE:~0,4%
SET MONTH=%DATE:~5,2%
SET DAY=%DATE:~8,2%
ECHO %YEAR%
ECHO %MONTH%
ECHO %DAY%
SET DATE_FRM=%YEAR%-%MONTH%-%DAY%
ECHO %DATE_FRM%
I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.
:: Check your local date format
echo %date%
:: Output is Mon 08/15/2016
:: get day (start index, number of characters)
:: (index starts with zero)
set myday=%DATE:~0,4%
echo %myday%
:: output is Mon
:: get month
set mymonth=%DATE:~4,2%
echo %mymonth%
:: output is 08
:: get date
set mydate=%DATE:~7,2%
echo %mydate%
:: output is 15
:: get year
set myyear=%DATE:~10,4%
echo %myyear%
:: output is 2016
I note that the o/p did not ask for a region-independent solution. My solution is for the UK though.
This is the simplest possible solution, a 1-line solution, for use in a Batch file:
FOR /F "tokens=1-3 delims=/" %%A IN ("%date%") DO (SET today=%%C-%%B-%%A)
echo %today%
This solution can be varied, by altering the order of the variables %%A %%B and %%C in the output statement, to provide any date format desired (e.g. YY-MM-DD or DD-MM-YY).
My intention - my ONLY intention - in posting this answer is to demonstrate that this can be done on the command line, by using a single line of code to achieve it.
And that it is redundant to post answers running to 35 lines of code, as others have done, because the o/p specifically asked for a command line solution in the question. Therefore the o/p specifically sought a single-line solution.

Resources