¿Cómo obtengo la fecha y hora actual en la línea de comandos de Windows, en un formato adecuado para usar en un nombre de archivo?


Actualización: Ahora que es 2016 usaría PowerShell para esto a menos que haya una razón realmente convincente compatible con versiones anteriores, particularmente debido al problema de configuración regional con el uso de date. Ver @npocmaka's https://stackoverflow.com/a/19799236/8479


¿Qué es una instrucción de línea de comandos de Windows que puedo usar para obtener la fecha y hora actual en un formato que pueda poner en un nombre de archivo?

Quiero tener un .archivo bat que comprime un directorio en un archivo con la fecha y hora actuales como parte del nombre, por ejemplo, Code_2008-10-14_2257.zip. ¿Hay alguna manera fácil de hacer esto, independientemente de la configuración regional de la máquina?

Realmente no me importa el formato de fecha, idealmente sería aaaa-mm-dd, pero cualquier cosa simple está bien.

Hasta ahora tengo esto, que en mi máquina me da 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

Puedo vivir con esto, pero parece un poco torpe. Idealmente sería más breve y tendría el formato mencionado anteriormente.

Estoy usando Windows Server 2003 y Windows XP Professional. No quiero instalar utilidades adicionales para lograr esto (aunque me doy cuenta de que hay algunas que harán un buen formato de fecha).

Author: Peter Mortensen, 2008-10-15

26 answers

Véase Archivo por lotes de Windows (.mtd) para obtener la fecha actual en formato MMDDYYYY:

@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%

Si prefiere el tiempo en formato 24 horas/militar, puede reemplazar la segunda línea de FOR con esto:

For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

C:> .\fecha.mtd
2008-10-14_0642

Si desea que la fecha sea independiente del orden día/mes de la región, puede usar "WMIC os GET LocalDateTime" como fuente, ya que está en orden ISO:

@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:>prueba.cmd
Local la fecha es [2012-06-19 10:23:47.048]

 604
Author: Jay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-15 11:39:48

Regionally independent date time parsing

El formato de salida de %DATE% y del comando dir es regionalmente dependiente y, por lo tanto, ni robusto ni inteligente. fecha.exe (parte de UnxUtils) entrega cualquier información de fecha y hora en cualquier formato pensable. También puede extraer la información de fecha / hora de cualquier archivo con date.exe.

Ejemplos: (en un script cmd use %% en lugar de%)

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: Cualquier texto

date.exe +"Text: %y/%m/%d-any text-%H.%M"
Texto: 09/12/22-cualquier texto-18.55

Command: date.exe +"%m-%d """%H %M %S """"
07-22 "18:55:03"`

La información de fecha / hora de un archivo de referencia:
date.exe -r c:\file.txt +"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S"

Usándolo en un script CMD para obtener información de año, mes, día, hora:

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

Usándolo en un script CMD para obtener una marca de tiempo en cualquier formato requerido:

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

Extrayendo la información de fecha / hora de cualquier referencia 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

Añadiendo a un archivo su información de fecha/hora:

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

Fecha.exe es parte de las herramientas libres de GNU que no necesitan instalación.

NOTA: Copiar date.exe en cualquier directorio que esté en la ruta de búsqueda puede causar que otros scripts fallen que usen el comando integrado de Windows date.

 93
Author: Uri Liebeskind,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-01 16:05:45

Dos formas más que no dependen de la configuración de tiempo (ambas tomadas de : Cómo obtener datos/tiempo independiente de la localización:). Y ambos también obtienen el día de la semana y ninguno de ellos requiere permisos de administrador!:

  1. MAKECAB - funcionará en TODOS los sistemas Windows (rápido, pero crea un pequeño archivo temporal) (el script foxidrive):

    @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
    

    Más información sobre la función get-date .

  2. ROBOCOPY - no es un comando nativo para Windows XP y Windows Server 2003, pero puede ser descargado desde el sitio de microsoft. Pero está incorporado en todo, desde Windows Vista y superiores:

    @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
    

    Y tres formas más que utiliza otros lenguajes de script de Windows. Le darán más flexibilidad, por ejemplo, puede obtener la semana del año,el tiempo en milisegundos, etc.

  3. JScript / batch híbrido (debe guardarse como .bat). JScript está disponible en todos los formularios del sistema NT y superior, como parte de Windows Script Host (aunque se puede desactivar a través del registro es un caso raro):

    @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 híbrido (¿Es posible incrustar y ejecutar VBScript dentro de un archivo por lotes sin usar un archivo temporal?) el mismo caso que JScript, pero la hibridación no es tan perfecta:

    :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 - se puede instalar en todas las máquinas que tengan. NET - descargar desde Microsoft (v1, v2, v3 (solo para Windows 7 y superior)). Se instala por defecto en todo desde Windows 7 / Windows Server 2008 y superior:

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

    Para usarlo desde un archivo por lotes:

    for /f "delims=" %%# in ('powershell get-date -format "{dd-MMM-yyyy HH:mm}"') do @set _date=%%#
    
  6. Autocompilado jscript.net/batch (nunca he visto una máquina Windows sin. NET, así que creo que esto es bastante portátil):

    @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 Esto no puede obtener el año y el día de la semana. Es relativamente lento y también crea un archivo temporal y se basa en las marcas de tiempo que logman pone en sus archivos de registro. Funcionará en todo, desde Windows XP y superiores. Probablemente nunca será utilizado por nadie, incluyéndome a mí, pero es una forma más...

    @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. Una forma más con WMIC que también da la semana del año y el día de la semana, pero no los milisegundos (para milisegundos verifique la respuesta de 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. Utilizando TYPEPERF con algunos esfuerzos para ser rápido y compatible con diferentes configuraciones de idioma y lo más rápido posible:

    @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 permite llamar a métodos JavaScript similares al método JScript demostrado en #3 arriba. Tenga en cuenta que las propiedades del objeto Date de JavaScript que involucran valores de mes están numeradas de 0 a 11, no de 1 a 12. Así que un valor de 9 significa octubre.

    <!-- : 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>
    
 73
Author: npocmaka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-15 17:52:51

Aquí hay una variante de alt.msdos.lote.nt que trabaja local-independientemente.

Pon esto en un archivo de texto, por ejemplo 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<-------------

Para conseguir que el código funcione sin errores de msg a stderr, tuve que agregar las comillas simples arount las asignaciones de variables para %%a, %%b y %%c. Mi configuración regional (PT) estaba causando errores en una etapa en el bucle/análisis donde cosas como "set =20" se estaba ejecutando. Las comillas producen un token (aunque vacío) para el lado izquierdo de la asignación instrucción.

El inconveniente son los desordenados nombres de variables locales: 'yy', 'mm' y 'dd'. ¡Pero a quién le importa!

 42
Author: vMax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-08 10:50:58

Utilizo esto (de nuevo no independiente de la región (Reino Unido))

set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%
 29
Author: bluish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-15 08:48:45

Desafortunadamente esto no es inmune a la configuración regional, pero hace lo que usted quiere.

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%

Increíble lo que puedes encontrar en Wikipedia.

 22
Author: Mark Ransom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-14 22:43:39

Utilice el siguiente script para obtener el día actual en la línea de comandos:

echo %Date:~0,3%day
 16
Author: sudipto roy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-12 11:50:42

Las primeras cuatro líneas de este código le darán variables fiables YY DD MM YYYY HH Min Sec en Windows XP Professional y superiores.

@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
 15
Author: foxidrive,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-15 17:58:04

Otra manera ( crédito):

@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%

Tenga en cuenta que mis dos respuestas aquí todavía dependen del orden del día y del mes según lo determinado por la configuración regional, no estoy seguro de cómo evitarlo.

 14
Author: J c,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-14 22:36:49
"d:\Program Files\7-Zip\7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip
 13
Author: DigiP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-20 11:13:11

Esto no es realmente más breve, pero podría ser una forma más flexible (crédito):

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%
 13
Author: J c,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-23 21:04:48

Aquí hay una manera de obtener la fecha y hora en una sola línea:

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

En los EE.UU. esto producirá "aaaa-mm-dd hhmm". Diferentes configuraciones regionales darán como resultado diferentes salidas %date%, pero puede modificar el orden del token.

Si desea un formato diferente, modifique la sentencia echo reordenando los tokens o utilizando separadores diferentes (o no).

 9
Author: Matthew Johnson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-04 20:57:03

Respuesta corta:

 :: 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 

Respuesta larga

    @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
 8
Author: Yordan Georgiev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-28 12:32:30

Y aquí hay un archivo por lotes similar para la porción de tiempo.

:: 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

Jer jeroen

 7
Author: Jeroen Wiert Pluimers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-03 13:26:05

Cambié la respuestacon el archivo por lotes de vMax para que también funcione con el idioma holandés.
Los holandeses - persistentes como somos-tienen algunos cambios en el %date%, date/t, y date que rompen el archivo por lotes original.

Sería bueno si algunas personas pueden comprobar esto contra otros locales de Windows, así, e informar de los resultados.
Si el archivo por lotes falla en su ubicación, incluya la salida de estas dos instrucciones en el comando prompt:
echo:^|date
date/t

Esta es una muestra de la salida que debe obtener del archivo por lotes:

C:\temp>set-date-cmd.bat
Today is Year: [2011] Month: [01] Day: [03]
20110103

Aquí está el código revisado con comentarios sobre el por qué:

:: 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 [email protected] 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

Jer jeroen

 7
Author: Jeroen Wiert Pluimers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:21

La solución de Matthew Johnson one-liner para obtener la fecha y hora de one-liner es elocuente y útil.

Sin embargo, necesita una simple modificación para trabajar desde dentro de un archivo por lotes:

for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e
 7
Author: John Langstaff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-14 13:00:36

Simplemente use esta línea:

PowerShell -Command "get-date"
 6
Author: gdelfino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-19 08:51:50

Una función que se basa en 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

Lado positivo: Independiente de la región. Inconveniente: Solo los administradores del sistema pueden ejecutar wmic.exe.

Uso:

call:Now Y M D H N S
echo %Y%-%M%-%D% %H%:%N%:%S%

Esto hace eco a una cadena como esta:

2014-01-22 12:51:53

Tenga en cuenta que los parámetros de la función son out-Parameters, es decir, debe proporcionar nombres de variables en lugar de valores.

Todos los parámetros son opcionales, por lo que call:Now Y M es una llamada válida si solo desea obtener year y month.

 6
Author: Tomalak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-15 17:55:45

Esto es lo que he usado:

::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:-=.%

Si desea más ideas para automatizar copias de seguridad en archivos 7-Zip, tengo un proyecto libre/abierto que puede usar o revisar para obtener ideas: http://wittman.org/ziparcy /

 5
Author: micahwittman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-15 11:40:29

Tuve un problema similar. Tengo una descarga diaria automática desde un servidor FTP de un archivo cifrado. Quería descifrar el archivo usando gpg, renombrar el archivo a la fecha actual (formato YYYYMMDD) y soltar el archivo descifrado en una carpeta para el departamento correcto.

Pasé por varias sugerencias para cambiar el nombre del archivo de acuerdo a la fecha y no estaba teniendo suerte hasta que me topé con esta solución simple.

for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt

Funcionó perfectamente (es decir, el nombre del archivo sale como "2011-06-14.txt").

(Fuente)

 4
Author: KChiki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-15 08:49:40

Http://sourceforge.net/projects/unxutils/files /

Busque dentro del archivo ZIP algo llamado "Fecha.exe "y renombrarlo" DateFormat.exe" (para evitar conflictos).

Colóquelo en su carpeta Windows system32.

Tiene muchas opciones de "salida de fecha".

Para obtener ayuda, use DateFormat.exe --h

No estoy seguro de cómo poner su salida en una variable de entorno... usando SET.

 4
Author: Sally,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-15 17:40:27

Solución regional independiente que genera el formato de fecha ISO:

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:

Lo que todavía podría optimizarse: Otros procesos pueden confundirse si se utiliza el formato de fecha en el corto período mientras se modifica. Por lo tanto, analizar la salida de acuerdo con la cadena de formato existente podría ser 'más seguro', pero será más complicado

 3
Author: V15I0N,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-06 12:09:39
:: 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 [email protected]
:: - 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
 1
Author: Adolfo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-11 15:42:11

Dada una localidad conocida, para referencia en forma funcional. La llamada ECHOTIMESTAMP muestra cómo obtener la marca de tiempo en una variable (DTS en este ejemplo.)

@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

Y guardado en el archivo, marca de tiempo.bat, aquí está la salida:

introduzca la descripción de la imagen aquí

 0
Author: bvj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-11 20:07:16

Con Windows 7, este código funciona para mí:

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%
 0
Author: Frizz1977,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-30 20:40:26

Sé que ya se han mencionado muchas maneras. Pero aquí está mi manera de desglosarlo para entender cómo se hace. Con suerte, es útil para alguien que le gusta el método paso a paso.

:: 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
 -2
Author: Cricrazy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-15 15:57:00