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

前端 未结 28 2073
别跟我提以往
别跟我提以往 2020-11-21 05:28

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 setting

相关标签:
28条回答
  • 2020-11-21 05:39

    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]

    0 讨论(0)
  • 2020-11-21 05:39

    Please use the following script to get the current day in the command line:

    echo %Date:~0,3%day
    
    0 讨论(0)
  • 2020-11-21 05:40

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

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

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

      More information about get-date function.

    2. 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.

    3. JScript/batch hybrid (need to be saved as .bat). JScript is available on every system form NT and above, as a part of Windows Script Host (though can be disabled through the registry it's a rare case):

      @if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment
      
      @echo off
      cscript //E:JScript //nologo "%~f0"
      exit /b 0
      *------------------------------------------------------------------------------*/
      
      function GetCurrentDate() {
              // Today date time which will used to set as default date.
              var todayDate = new Date();
              todayDate = todayDate.getFullYear() + "-" +
                             ("0" + (todayDate.getMonth() + 1)).slice(-2) + "-" +
                             ("0" + todayDate.getDate()).slice(-2) + " " + ("0" + todayDate.getHours()).slice(-2) + ":" +
                             ("0" + todayDate.getMinutes()).slice(-2);
      
              return todayDate;
          }
      
      WScript.Echo(GetCurrentDate());
      
    4. VSCRIPT/BATCH hybrid (Is it possible to embed and execute VBScript within a batch file without using a temporary file?) same case as JScript, but hybridization is not so perfect:

      :sub echo(str) :end sub
      echo off
      '>nul 2>&1|| copy /Y %windir%\System32\doskey.exe %windir%\System32\'.exe >nul
      '& echo current date:
      '& cscript /nologo /E:vbscript "%~f0"
      '& exit /b
      
      '0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
      '1 = vbLongDate - Returns date: weekday, monthname, year
      '2 = vbShortDate - Returns date: mm/dd/yy
      '3 = vbLongTime - Returns time: hh:mm:ss PM/AM
      '4 = vbShortTime - Return time: hh:mm
      
      WScript.echo  Replace(FormatDateTime(Date,1),", ","-")
      
    5. PowerShell - can be installed on every machine that has .NET - download from Microsoft (v1, v2, v3 (only for 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=%%#
      
    6. Self-compiled jscript.net/batch (never seen a Windows machine without .NET, so I think this is a pretty portable):

      @if (@X)==(@Y) @end /****** silent line that start JScript comment ******
      
      @echo off
      ::::::::::::::::::::::::::::::::::::
      :::       Compile the script    ::::
      ::::::::::::::::::::::::::::::::::::
      setlocal
      if exist "%~n0.exe" goto :skip_compilation
      
      set "frm=%SystemRoot%\Microsoft.NET\Framework\"
      
      :: Searching the latest installed .NET framework
      for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
          if exist "%%v\jsc.exe" (
              rem :: the javascript.net compiler
              set "jsc=%%~dpsnfxv\jsc.exe"
              goto :break_loop
          )
      )
      echo jsc.exe not found && exit /b 0
      :break_loop
      
      
      call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
      ::::::::::::::::::::::::::::::::::::
      :::       End of compilation    ::::
      ::::::::::::::::::::::::::::::::::::
      :skip_compilation
      
      "%~n0.exe"
      
      exit /b 0
      
      
      ****** End of JScript comment ******/
      import System;
      import System.IO;
      
      var dt=DateTime.Now;
      Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss"));
      
    7. Logman This cannot get the year and day of the week. It's comparatively slow 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
      
    8. 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%
      
    9. 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
      
    10. 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>
      
    0 讨论(0)
  • 2020-11-21 05:40

    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/

    0 讨论(0)
  • 2020-11-21 05:41

    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.

    0 讨论(0)
  • 2020-11-21 05:41

    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%
    
    0 讨论(0)
提交回复
热议问题