How to append a date in batch files - windows

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.

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.

Windows Batch file - Date parse inside IF does not work

I'm trying to parse date inside an IF statement, my actual code is slightly more complex than one below quoted (i'd use EnableDelayedExpansion) but still the date parsing is behaving weird to me.
the expected output of the "ECHO" command would have been during my last attempt BK_20141111_1030.7z but it is shown as BK_20141111_10:30.7z. If i move the line
Set PARSEARG="eol=; tokens=1,2,3* delims=:, "
outside the IF statement the output is correctly shown. Is it possible to parse delimiters within an IF clause?
DATE /T stores data in format GG/MM/YYYY (or MM/GG/YYYY)
TIME /T stores time in format HH:mm
#echo off
:cmpct
Set CURRDATE=%TEMP%\CURRDATE.TMP
Set CURRTIME=%TEMP%\CURRTIME.TMP
DATE /T > %CURRDATE%
TIME /T > %CURRTIME%
Set PARSEARG="eol=; tokens=1,2,3,4* delims=/, "
For /F %PARSEARG% %%i in (%CURRDATE%) Do SET YYYYMMDD=%%k%%j%%i
if 1==1 (
Set PARSEARG="eol=; tokens=1,2,3* delims=:, "
For /F %PARSEARG% %%i in (%CURRTIME%) Do Set HHMM=%%i%%j%%k
echo BK_%YYYYMMDD%_%HHMM%.7z
)
)
#echo off
:cmpct
Set PARSEARG="eol=; tokens=1,2,3,4* delims=/, "
For /F %PARSEARG% %%i in ("%DATE%") Do SET YYYYMMDD=%%k%%j%%i
rem echo %time%
setlocal enableDelayedExpansion
if 1==1 (
For /F "eol=; tokens=1,2,3* delims=:, " %%i in ("%time%") Do (
Set HHMM=%%i%%j%%k
echo BK_%YYYYMMDD%_!HHMM!.7z
rem %time%
)
)
if 2==2 (
For /F "eol=; tokens=1,2,3* delims=:, " %%i in ("%time%") Do (
Set HHMM=%%i%%j%%k
echo BK_%YYYYMMDD%_!HHMM!.7z
rem %time%
)
)
endlocal
?
EDIT
I saw your memo and updated my answer.
You cannot parametrize the FOR command with delayed expansion.
the %variables% are expanded during the parsing of the script.
the !variables! (delayed expansion) are expanded during the execution.
But FOR command checks it's syntax during parsing so using FOR !options! will always lead to parsing error. So the only option you have is multiple IF conditions or a subroutine.

Safe way to get current day month and year in batch

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

Creating a file name as a timestamp in a batch job

We have a batch job that runs every day and copies a file to a pickup folder. I want to also take a copy of that file and drop it into an archive folder with the filename
yyyy-MM-dd.log
What's the easiest way to do this in a Windows batch job?
I'm basically looking for an equivalent of this Unix command:
cp source.log `date +%F`.log
CP source.log %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%.log
But it's locale dependent. I'm not sure if %DATE% is localized, or depends on the format specified for the short date in Windows.
Here is a locale-independent way to extract the current date from this answer, but it depends on WMIC and FOR /F:
FOR /F %%A IN ('WMIC OS GET LocalDateTime ^| FINDSTR \.') DO #SET B=%%A
CP source.log %B:~0,4%-%B:~4,2%-%B:~6,2%.log
This worked for me and was a filename-safe solution (though it generates a MM-dd-YYYY format):
C:\ set SAVESTAMP=%DATE:/=-%#%TIME::=-%
C:\ set SAVESTAMP=%SAVESTAMP: =%
C:\ set SAVESTAMP=%SAVESTAMP:,=.%.jpg
C:\ echo %SAVESTAMP%
11-04-2012#20-52-42.79.jpg
The first command takes a DATE and replaces / with -, takes the TIME and replaces : with -, and combines them into DATE#TIME format. The second set statement removes any spaces, and the third set replaces , with . and appends the .jpg extension.
The above code is used in a little script that pulls images from a security IP Camera for further processing:
:while
set SAVESTAMP=%DATE:/=-%#%TIME::=-%
set SAVESTAMP=%SAVESTAMP: =%
set SAVESTAMP=%SAVESTAMP:,=.%.jpg
wget-1.10.2.exe --tries=0 -O %SAVESTAMP% http://admin:<password>#<ip address>:<port>/snapshot.cgi
timeout 1
GOTO while
For French Locale (France) ONLY, be careful because / appears in the date :
echo %DATE%
08/09/2013
For our problem of log file, here is my proposal for French Locale ONLY:
SETLOCAL
set LOGFILE_DATE=%DATE:~6,4%.%DATE:~3,2%.%DATE:~0,2%
set LOGFILE_TIME=%TIME:~0,2%.%TIME:~3,2%
set LOGFILE=log-%LOGFILE_DATE%-%LOGFILE_TIME%.txt
rem log-2014.05.19-22.18.txt
command > %LOGFILE%
Because the idea of tearing %DATE% and %TIME% apart and mashing them back together seems fragile at best, here's an alternative that uses a powershell oneliner:
for /f %i in ('powershell -c "get-date -format yyyy-MM-dd--HH-mm-ss"') do #set DATETIME=%i
set LOGFILE=my-script-%DATETIME%.txt
Reference for get-date is here, with format options for both .NET-style and UNIX-style.
Here is a locale independent solution (copy to a file named SetDateTimeComponents.cmd):
#echo off
REM This script taken from the following URL:
REM http://www.winnetmag.com/windowsscripting/article/articleid/9177/windowsscripting_9177.html
REM Create the date and time elements.
for /f "tokens=1-7 delims=:/-, " %%i in ('echo exit^|cmd /q /k"prompt $d $t"') do (
for /f "tokens=2-4 delims=/-,() skip=1" %%a in ('echo.^|date') do (
set dow=%%i
set %%a=%%j
set %%b=%%k
set %%c=%%l
set hh=%%m
set min=%%n
set ss=%%o
)
)
REM Let's see the result.
echo %dow% %yy%-%mm%-%dd% # %hh%:%min%:%ss%
I put all my .cmd scripts into the same folder (%SCRIPTROOT%); any script that needs date/time values will call SetDateTimeComponents.cmd as in the following example:
setlocal
#echo Initializing...
set SCRIPTROOT=%~dp0
set ERRLOG=C:\Oopsies.err
:: Log start time
call "%SCRIPTROOT%\SetDateTimeComponents.cmd" >nul
#echo === %dow% %yy%-%mm%-%dd% # %hh%:%min%:%ss% : Start === >> %ERRLOG%
:: Perform some long running action and log errors to ERRLOG.
:: Log end time
call "%SCRIPTROOT%\SetDateTimeComponents.cmd" >nul
#echo === %dow% %yy%-%mm%-%dd% # %hh%:%min%:%ss% : End === >> %ERRLOG%
As the example shows, you can call SetDateTimeComponents.cmd whenever you need to update the date/time values. Hiding the time parsing script in it's own SetDateTimeComponents.cmd file is a nice way to hide the ugly details, and, more importantly, avoid typos.
I frequently use this, and put everything into a single copy command. The following copies example.txt as example_YYYYMMDD_HHMMSS.txt and of course you can modify it to suit your preferred format. The quotes are only necessary if there are any spaces in the filespec. If you want to reuse the exact same date/timestamp, you'd need to store it in a variable.
copy "{path}\example.txt" "{path}\_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt"
This will ensure that the output is a 2-digit value...you can rearrange the output to your liking and test by un-commenting the diagnostics section. Enjoy!
(I borrowed a lot of this from other forums...)
:: ------------------ Date and Time Modifier ------------------------
#echo off
setlocal
:: THIS CODE WILL DISPLAY A 2-DIGIT TIMESTAMP FOR USE IN APPENDING FILENAMES
:: CREATE VARIABLE %TIMESTAMP%
for /f "tokens=1-8 delims=.:/-, " %%i in ('echo exit^|cmd /q /k"prompt $D $T"') do (
for /f "tokens=2-4 skip=1 delims=/-,()" %%a in ('echo.^|date') do (
set dow=%%i
set %%a=%%j
set %%b=%%k
set %%c=%%l
set hh=%%m
set min=%%n
set sec=%%o
set hsec=%%p
)
)
:: ensure that hour is always 2 digits
if %hh%==0 set hh=00
if %hh%==1 set hh=01
if %hh%==2 set hh=02
if %hh%==3 set hh=03
if %hh%==4 set hh=04
if %hh%==5 set hh=05
if %hh%==6 set hh=06
if %hh%==7 set hh=07
if %hh%==8 set hh=08
if %hh%==9 set hh=09
:: --------- TIME STAMP DIAGNOSTICS -------------------------
:: Un-comment these lines to test output
:: echo dayOfWeek = %dow%
:: echo year = %yy%
:: echo month = %mm%
:: echo day = %dd%
:: echo hour = %hh%
:: echo minute = %min%
:: echo second = %sec%
:: echo hundredthsSecond = %hsec%
:: echo.
:: echo Hello!
:: echo Today is %dow%, %mm%/%dd%.
:: echo.
:: echo.
:: echo.
:: echo.
:: pause
:: --------- END TIME STAMP DIAGNOSTICS ----------------------
:: assign timeStamp:
:: Add the date and time parameters as necessary - " yy-mm-dd-dow-min-sec-hsec "
endlocal & set timeStamp=%yy%%mm%%dd%_%hh%-%min%-%sec%
echo %timeStamp%
Create a file with the current date as filename (ex. 2008-11-08.dat)
echo hello > %date%.dat
With the current date but without the "-" (ex. 20081108.dat)
echo hello > %date:-=%.dat
Maybe this can help:
echo off
#prompt set date=$d$_ set time=$t$h$h$h
echo some log >> %date% %time%.log
exit
or
echo off
set v=%date%.log
echo some log >> %v%
I put together a little C program to print out the current timestamp (locale-safe, no bad characters...). Then, I use the FOR command to save the result in an environment variable:
:: Get the timestamp
for /f %%x in ('#timestamp') do set TIMESTAMP=%%x
:: Use it to generate a filename
for /r %%x in (.\processed\*) do move "%%~x" ".\archived\%%~nx-%TIMESTAMP%%%~xx"
Here's a link:
https://github.com/HarryPehkonen/dos-timestamp
I know this thread is old but I just want to add this here because it helped me alot trying to figure this all out and its clean. The nice thing about this is you could put it in a loop for a batch file that's always running. Server up-time log or something. That's what I use it for anyways. I hope this helps someone someday.
#setlocal enableextensions enabledelayedexpansion
#echo off
call :timestamp freshtime freshdate
echo %freshdate% - %freshtime% - Some data >> "%freshdate - Somelog.log"
:timestamp
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
set FreshTime=%hour%:%min%:%secs%
set year=%date:~-4%
set month=%date:~4,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
set day=%date:~7,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
set FreshDate=%month%.%day%.%year%
You can simply detect the current local format and can get the date in your format, for example:
::for 30.10.2016 dd.MM.yyyy
if %date:~2,1%==. set d=%date:~-4%%date:~3,2%%date:~,2%
::for 10/30/2016 MM/dd/yyyy
if %date:~2,1%==/ set d=%date:~-4%%date:~,2%%date:~3,2%
::for 2016-10-30 yyyy-MM-dd
if %date:~4,1%==- set d=%date:~,4%%date:~5,2%%date:~-2%
::variable %d% have now value: 2016103 (yyyyMMdd)
set t=%time::=%
set t=%t:,=%
::variable %t% have now time without delimiters
cp source.log %d%_%t%.log
I know this is an old post, but there is a FAR simpler answer (though maybe it only works in newer versions of windows). Just use the /t parameter for the DATE and TIME dos commands to only show the date or time and not prompt you to set it, like this:
#echo off
echo Starting test batch file > testlog.txt
date /t >> testlog.txt
time /t >> testlog.txt
1) You can download GNU coreutils which comes with GNU date
2) you can use VBScript, which makes date manipulation easier in Windows:
Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder = "c:\test"
Set objFolder = objFS.GetFolder(strFolder)
current = Now
mth = Month(current)
d = Day(current)
yr = Year(current)
If Len(mth) <2 Then
mth="0"&mth
End If
If Len(d) < 2 Then
d = "0"&d
End If
timestamp=yr & "-" & mth &"-"& d
For Each strFile In objFolder.Files
strFileName = strFile.Name
If InStr(strFileName,"file_name_here") > 0 Then
BaseName = objFS.GetBaseName(strFileName)
Extension = objFS.GetExtensionName(strFileName)
NewName = BaseName & "-" & timestamp & "." & Extension
strFile.Name = NewName
End If
Next
Run the script as:
c:\test> cscript /nologo myscript.vbs
This works well with (my) German locale, should be possible to adjust it to your needs...
forfiles /p *PATH* /m *filepattern* /c "cmd /c ren #file
%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%_#file"
For big zip files for deployment, I use quarter hours. No one else on this page had mentioned it before, so I'll put my small script here:
set /a "quarter_hours=%time:~0,2%*4 + %time:~3,2% / 15"
set "zip_file=release_%DATE:~-4%.%DATE:~4,2%.%DATE:~7,2%.%quarter_hours%.zip"
It doesn't zero pad quarter hours from midnight to 5am yet, but it still makes it so you can have a stamped release multiple times a day with few collisions.
Hope that helps.
used Martin's suggestion with a little tweak to add time stamp to the file name:
forfiles /p [foldername] /m rsync2.log /c "cmd /c ren #file %DATE:~6,4%%DATE:~3,2%%DATE:~0,2%_%time:~-11,2%-%time:~-8,2%-%time:~-5,2%-#file
For the 10:17:21 23/10/2019 The result is:
20191023_10-17-21-rsync2.log
echo Date and Time: %date% %time%
rem 29/09/2021 10:01:34,23
set timestamp=%time: =0%
set timestamp=%timestamp::=%
set timestamp=%timestamp:,=%
set timestamp=%date:/=%%timestamp%
echo Timestamp (ddMMYYYYHHmmssms): %timestamp%
rem 2909202109543118
set timestamp=%timestamp:~4,4%%timestamp:~2,2%%timestamp:~0,2%%timestamp:~8,8%
echo Timestamp (YYYYMMddHHmmssms) %timestamp%
rem 2021092910013423
Notice that you could be a little bit more flexible by using negative indexes...
It will fit both English and West Europe date formats (of course with switched positions between days and months)
echo %DATE:~-10,2%%DATE:~-7,2%T%TIME:~0,2%%TIME:~3,2%
This is a 12 year old thread, but still active, and there has not yet been a truly locale-independent batch-only solution so here's my tuppence.
This should work on any windows setup, regardless of your local date settings. To be sure you get the correct DD MM and YYYY parts of the date you need to change the registry short-date format. Try this:
Store current registry short-date format in a local variable
Set the registry format to YYYYMMDD (or whatever you want)
Store current date to a local variable
Reset registry back to the original format
I keep the script below in 'YYYYMMDD.bat' and call it as needed.
#echo off
:: Create environment variable containing current date in YYYYMMDD format.
:: Intended to be called from other batch jobs
::Save current registry date format
for /f "tokens=2*" %%a in ('reg query "HKCU\Control Panel\International" /v sShortDate^|find "REG_SZ"') do set "ssShortDate=%%b"
::Change registry date format to yyyymmdd
reg add "HKCU\Control Panel\International" /f /v sShortDate /d "yyyyMMdd" >nul
::Save current date in yyyymmdd format
set "YYYYMMDD=%date%"
::Restore original format to registry
reg add "HKCU\Control Panel\International" /f /v sShortDate /d "%ssShortDate%" >nul
echo YYYYMMDD=%YYYYMMDD%
timeout /t:1 >nul
exit /b

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