How do I get the current date / time in the appropriate format on the Windows command line to use in the file / folder name?

Update: it's 2016, and unless there's a really compelling reason for backward compatibility, I'll use PowerShell, especially because of the locale issues with date. See @ npocmaka's https://stackoverflow.com/a/19799236/8479

What is a Windows command line statement that I can use to get the current date and time in a format that can be put into a file name?

I want a. bat file, which compresses the directory into an archive and takes the current date and time as part of the name, such as code  2008-10-14  2257.zip. Is there an easy way to do this regardless of the machine's locale?

I don't care much about date format, ideally yyyy MM DD, but any simple way is OK.

So far, I've learned that on my machine, this gave 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 stand it, but it seems a bit clumsy. Ideally, it would be shorter and have the format mentioned earlier.

I am using Windows Server 2003 and Windows XP Professional. I don't want to install other utilities to do this (although I know some utilities format dates well).

#1 building

Matthew Johnson's single line solution To get a single line date and time is eloquent and useful.

However, it does require simple modifications to work in a batch file:

for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e

#2 building

"d:\Program Files\7-Zip\7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip

#3 building

Region independent date time resolution

%The output format of the DATE% and dir commands depends on the region, so they are neither robust nor wise. date.exe ( UnxUtils Part) provide any date and time information in any format that can be considered. You can also use date.exe to extract date / time information from any file.

Example: (use%% in cmd script 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"`

Date / time information in reference:
date.exe -rc:\\file.txt +"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S"

Use it in the CMD script to get the year, month, day, and 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

Use it in the CMD script to get the timestamp in any desired format:

for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe +"%%y-%%m-%%d %%H:%%M:%%S"') do set timestamp=%%i

Extract date / time information from any reference.

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

Add the date / time information of the file to the file:

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 tool, No installation required.

Note: copying date.exe to any directory in the search path may cause other scripts that use the Windows built-in date command to fail.

#4 building

The other two methods are independent of time setting (both are taken from : how to get localization independent data / time:) . Both can get the day of the week, and do not need administrator permission! :

  1. MAKECAB - will run on every Windows system (fast, but will create a small temporary file) (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 about the get date function .

  2. ROBOCOPY - it is not a native command of Windows XP and Windows Server 2003, but it can Download from Microsoft website . But everything built into Windows Vista and later:

    @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

    There are three other ways to use other Windows scripting languages. They will give you more flexibility, for example, you can get weeks of the year, milliseconds and so on.

  3. JScript / batch mix (need to save as. bat). Act as Windows Script Host Part of JScript in Windows NT or higher on all systems All available ( Although it can be disabled through the registry, this is rare ):

    @if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment @echo off cscript //E:JScript //nologo "%~f0" exit /b 0 *------------------------------------------------------------------------------*/ function GetCurrentDate() { // Today date time which will used to set as default date. var todayDate = new Date(); todayDate = todayDate.getFullYear() + "-" + ("0" + (todayDate.getMonth() + 1)).slice(-2) + "-" + ("0" + todayDate.getDate()).slice(-2) + " " + ("0" + todayDate.getHours()).slice(-2) + ":" + ("0" + todayDate.getMinutes()).slice(-2); return todayDate; } WScript.Echo(GetCurrentDate());
  4. VSCRIPT / BATCH mix( Whether temporary files can be used Under circumstances Embed and execute VBScript in batch files? )Same as JScript, but not so perfect:

    :sub echo(str) :end sub echo off '>nul 2>&1|| copy /Y %windir%\\System32\\doskey.exe %windir%\\System32\\'.exe >nul '& echo current date: '& cscript /nologo /E:vbscript "%~f0" '& exit /b '0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM. '1 = vbLongDate - Returns date: weekday, monthname, year '2 = vbShortDate - Returns date: mm/dd/yy '3 = vbLongTime - Returns time: hh:mm:ss PM/AM '4 = vbShortTime - Return time: hh:mm WScript.echo Replace(FormatDateTime(Date,1),", ","-")
  5. PowerShell - can be installed on every computer with. NET - download from Microsoft( v1v2v3 (Windows 7 and later only). By default, it will be installed on all components in Windows 7 / Windows Server 2008 and later:

    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=%%#
  6. Self compiled jscript.net/batch (never seen a Windows machine without. NET, so I think it's a portable tool):

    @if (@X)==(@Y) @end /****** silent line that start JScript comment ****** @echo off :::::::::::::::::::::::::::::::::::: ::: Compile the script :::: :::::::::::::::::::::::::::::::::::: setlocal if exist "%~n0.exe" goto :skip_compilation set "frm=%SystemRoot%\\Microsoft.NET\\Framework\\" :: Searching the latest installed .NET framework for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\\Microsoft.NET\\Framework\\v*"') do ( if exist "%%v\\jsc.exe" ( rem :: the javascript.net compiler set "jsc=%%~dpsnfxv\\jsc.exe" goto :break_loop ) ) echo jsc.exe not found && exit /b 0 :break_loop call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0" :::::::::::::::::::::::::::::::::::: ::: End of compilation :::: :::::::::::::::::::::::::::::::::::: :skip_compilation "%~n0.exe" exit /b 0 ****** End of JScript comment ******/ import System; import System.IO; var dt=DateTime.Now; Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss"));
  7. Logman can't get the year and day of the week. It is relatively slow and creates a temporary file based on the timestamp logman places on its log file. It can run on all operating systems of Windows XP and later. It may never be used by anyone - including me - but there is another 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
  8. Another way to use WMIC is to give the day of the week in a year and the day of the week in a week (but not milliseconds) (in milliseconds, see the answer to foxidrive):

    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%
  9. Use TYPEPERF Make some efforts to make it fast and compatible with different language settings and as soon 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
  10. MSHTA allows you to call JavaScript methods similar to the JScript method shown in 3 above. Keep in mind that the Date object property of JavaScript involving month values is numbered from 0 to 11, not from 1 to 12. Therefore, a value of 9 indicates 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>

#5 building

This is what I 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 to learn more about how to automatically back up a 7-Zip archive, I have a free / open project that you can use or view with ideas: http : //wittman.org/ziparcy/

Tags: Windows Javascript

Posted on Tue, 14 Jan 2020 02:42:32 -0800 by chris9902