Formatear la fecha y la hora en un script por lotes de Windows


En un script por lotes de Windows (Windows XP) necesito formatear la fecha y hora actuales para su uso posterior en nombres de archivos, etc.

Es similar a la pregunta de desbordamiento de pilaCómo añadir una fecha en archivos por lotes, pero con el tiempo también.

Tengo esto hasta ahora:

echo %DATE%
echo %TIME%
set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%
echo %datetimef%

Que da:

28/07/2009
 8:35:31.01
2009_07_28__ 8_36_01

¿Hay alguna manera de permitir una hora de un solo dígito en %TIME%, para que pueda obtener lo siguiente?

2009_07_28__08_36_01
Author: Community, 2009-07-28

30 answers

Terminé con este script:

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%

set year=%date:~-4%
echo year=%year%

:: On WIN2008R2 e. g. I needed to make your 'set month = % date:~3,2%' like below:: otherwise 00 appears for MONTH

set month=%date:~4,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
echo month=%month%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
echo day=%day%

set datetimef=%year%%month%%day%_%hour%%min%%secs%

echo datetimef=%datetimef%
 129
Author: laurie,
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-05-22 20:37:09
@ECHO OFF
: Sets the proper date and time stamp with 24Hr Time for log file naming
: convention

SET HOUR=%time:~0,2%
SET dtStamp9=%date:~-4%%date:~4,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2% 
SET dtStamp24=%date:~-4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%

if "%HOUR:~0,1%" == " " (SET dtStamp=%dtStamp9%) else (SET dtStamp=%dtStamp24%)

ECHO %dtStamp%

PAUSE
 63
Author: sth,
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
2009-09-19 15:11:09

Así es como genero un nombre de archivo de registro (basado en http://ss64.com/nt/syntax-getdate.html):

@ECHO OFF
:: Check WMIC is available
WMIC.EXE Alias /? >NUL 2>&1 || GOTO s_error

:: Use WMIC to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
   IF "%%~L"=="" goto s_done
      Set _yyyy=%%L
      Set _mm=00%%J
      Set _dd=00%%G
      Set _hour=00%%H
      SET _minute=00%%I
      SET _second=00%%K
)
:s_done

:: Pad digits with leading zeros
      Set _mm=%_mm:~-2%
      Set _dd=%_dd:~-2%
      Set _hour=%_hour:~-2%
      Set _minute=%_minute:~-2%
      Set _second=%_second:~-2%

Set logtimestamp=%_yyyy%-%_mm%-%_dd%_%_hour%_%_minute%_%_second%
goto make_dump

:s_error
echo WMIC is not available, using default log filename
Set logtimestamp=_

:make_dump
set FILENAME=database_dump_%logtimestamp%.sql
...
 54
Author: nightcoder,
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
2013-05-02 23:06:22

Si PowerShell está instalado, puede obtener de forma fácil y fiable la Fecha / hora en cualquier formato que desee, por ejemplo:

for /f %%a in ('powershell -Command "Get-Date -format yyyy_MM_dd__HH_mm_ss"') do set datetime=%%a
move "%oldfile%" "backup-%datetime%"

Por supuesto, hoy en día PowerShell siempre está instalado, pero en Windows XP probablemente solo querrá usar esta técnica si su script por lotes se está utilizando en un entorno conocido donde sabe que PS está disponible (o verifique en su archivo por lotes si PowerShell está disponible...)

Puede preguntar razonablemente: por qué usar un archivo por lotes si puede usar PowerShell para obtener la fecha / hora, pero creo que algunas razones obvias son: (a) no está tan familiarizado con PowerShell y aún prefiere hacer la mayoría de las cosas a la antigua con los archivos por lotes o (b) está actualizando un script antiguo y no quiere portar todo a PS.

 32
Author: G. Lombard,
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
2013-10-03 16:03:48

Me encontré con este problema hoy y lo resolví con:

SET LOGTIME=%TIME: =0%

Reemplaza espacios con 0s y básicamente cero-pads la hora.

Después de una búsqueda rápida no descubrí si requería extensiones de comando (todavía funcionaba con SETLOCAL DISABLEEXTENSIONS).

 27
Author: opello,
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-08-25 14:27:32

Normalmente lo hago de esta manera cada vez que necesito una cadena de fecha/hora:

set dt=%DATE:~6,4%_%DATE:~3,2%_%DATE:~0,2%__%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%
set dt=%dt: =0%

Esto es para el formato de fecha/hora alemán (dd.mm.aaaa hh:mm:ss). Básicamente concateno las subcadenas y finalmente reemplazo todos los espacios con ceros.

Breve explicación de cómo funcionan las subcadenas:

%VARIABLE:~num_chars_to_skip,num_chars_to_keep%

Así que para obtener solo el año a partir de una fecha como "29.03.2018" use:

%DATE:~6,4%
       ^-----skip 6 characters
         ^---keep 4 characters 
 27
Author: mrt,
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-04-16 04:10:37

Como se ha señalado, analizar la fecha y la hora solo es útil si conoce el formato que está utilizando el usuario actual (por ejemplo, MM/dd/aa o dd-MM-aaaa solo para nombrar dos). Esto podría ser determinado, pero en el momento en que haga todo el estrés y el análisis, todavía terminará con alguna situación donde hay un formato inesperado utilizado, y más ajustes serán necesarios.

También puede utilizar algún programa externo que devolverá una babosa de fecha en su formato preferido, pero que tiene desventajas de tener que distribuir el programa de utilidad con su script / lote.

También hay trucos por lotes usando el reloj CMOS de una manera bastante cruda, pero eso es demasiado cerca de los cables desnudos para la mayoría de las personas, y tampoco siempre es el lugar preferido para recuperar la fecha/hora.

A continuación se muestra una solución que evita los problemas anteriores. Sí, introduce algunos otros problemas, pero para mis propósitos encontré que esta es la solución más fácil, clara y portátil para crear una marca de fecha en .archivos bat para sistemas Windows modernos. Esto es solo un ejemplo, pero creo que verá cómo modificar para otros formatos de fecha y / o hora, 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 reg query "HKCU\Control Panel\International" /v sShortDate
set LogDate=%date%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f
 20
Author: jph,
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-06-18 21:04:57

¿La siguiente no puede ser una respuesta directa sino cercana?

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__0%time:~1,2%_%time:~3,2%_%time:~6,2%
else set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%

Al menos puede ser inspirador.

 8
Author: ufukgun,
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-06-18 21:01:43

Si no necesitas exactamente este formato:

2009_07_28__08_36_01

Entonces podría usar las siguientes 3 líneas de código que usa %date% y %time%:

set mydate=%date:/=%
set mytime=%time::=%
set mytimestamp=%mydate: =_%_%mytime:.=_%

Nota: Los caracteres / y : se eliminan y el carácter . y el espacio se reemplazan con un subrayado.

Salida de ejemplo (tomada el miércoles 8/5/15 a las 12: 49 PM con 50 segundos y 93 milisegundos):

echo %mytimestamp%
Wed_08052015_124950_93
 8
Author: Jesse,
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
2015-08-05 17:00:44
REM Assumes UK style date format for date environment variable (DD/MM/YYYY).
REM Assumes times before 10:00:00 (10am) displayed padded with a space instead of a zero.
REM If first character of time is a space (less than 1) then set DATETIME to:
REM YYYY-MM-DD-0h-mm-ss
REM Otherwise, set DATETIME to:
REM YYYY-MM-DD-HH-mm-ss
REM Year, month, day format provides better filename sorting (otherwise, days grouped
REM together when sorted alphabetically).

IF "%time:~0,1%" LSS "1" (
   SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-0%time:~1,1%-%time:~3,2%-%time:~6,2%
) ELSE (
   SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%
)

ECHO %DATETIME%
 6
Author: Mike Raynham,
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
2009-11-25 10:07:03

El offset:length formato compatible con el SET comando en Windows no le permitirá la almohadilla de la 0 como usted parece estar interesado en.

Sin embargo, puede codificar un script POR LOTES para verificar que la hora sea menor que 10 y
rellene en consecuencia con una cadena echo diferente.

Encontrará algunos información sobre el SET comando en este enlace.


También puede cambiar a otros métodos de programación para llegar aquí.

Es bastante simple en unix bash (disponible con Cygwin en Windows) decir simplemente,

date +%Y_%m_%d__%H_%M_%S

Y, siempre se rellena correctamente.

 5
Author: nik,
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
2009-07-28 08:41:38

Lo hice de esta manera:

REM Generate FileName from date and time in format YYYYMMTTHHMM

Time /T > Time.dat
set /P ftime= < Time.dat

set FileName=LogFile%date:~6%%date:~3,2%%date:~0,2%%ftime:~0,2%%ftime:~3,2%.log

echo %FileName%

LogFile201310170928.log

 4
Author: Ice,
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-06-18 21:08:40

Para generar una marca de tiempo YYYY-MM-DD hh:mm:ss (24 horas) uso:

SET CURRENTTIME=%TIME%
IF "%CURRENTTIME:~0,1%"==" " (SET CURRENTTIME=0%CURRENTTIME:~1%)
FOR /F "tokens=2-4 delims=/ " %%A IN ('DATE /T') DO (SET TIMESTAMP=%%C-%%A-%%B %CURRENTTIME%)
 3
Author: M. Dudley,
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-11-17 16:23:39
::========================================================================  
::== CREATE UNIQUE DATETIME STRING IN FORMAT YYYYMMDD-HHMMSS   
::======= ================================================================  
FOR /f %%a IN ('WMIC OS GET LocalDateTime ^| FIND "."') DO SET DTS=%%a  
SET DATETIME=%DTS:~0,8%-%DTS:~8,6%  

La primera línea siempre sale en este formato respecto a la zona horaria:
20150515150941.077000+120
Esto le deja con solo formatear la salida para que se ajuste a sus deseos.

 3
Author: Kees,
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
2015-05-15 13:14:21
set hourstr = %time:~0,2%
if "%time:~0,1%"==" " (set hourstr=0%time:~1,1%)
set datetimestr=%date:~0,4%%date:~5,2%%date:~8,2%-%hourstr%%time:~3,2%%time:~6,2%
 2
Author: Will Wu,
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
2013-11-21 01:22:52

Cree un archivo llamado "search_files.bat" y coloque el contenido de abajo en el archivo. A continuación, haga doble clic en él. La variable temporal % THH% fue implementada para manejar la MA apropiadamente. Si hay un 0 en los primeros 2 dígitos del tiempo, Windows ignora el resto del nombre del archivo del archivo de REGISTRO.

CD .
SET THH=%time:~0,2%
SET THH=%THH: =0%
dir /s /b *.* > %date:~10,4%-%date:~4,2%-%date:~7,2%@%THH%.%time:~3,2%.%time:~6,2%.LOG
 2
Author: MacGyver,
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-03-06 16:01:25

Este script por lotes hará exactamente lo que el O. P. quiere (probado en Windows XP SP3).

También utilicé ese truco de registro inteligente descrito por "jph" anteriormente, que en mi humilde opinión es la forma más sencilla de obtener un formato 100% consistente de la fecha de "yyyy_MM_dd" en cualquier sistema Windows nuevo o antiguo. El cambio a un valor de Registro para hacer esto es instantáneo temporal y trivial; solo dura unos pocos milisegundos antes de que se revierta inmediatamente.

Haga doble clic en este archivo por lotes para una demostración instantánea, la ventana del símbolo del sistema aparecerá y mostrará su marca de tiempo . . . . .

@ECHO OFF
SETLOCAL & MODE CON:COLS=80 LINES=15 & COLOR 0A
TITLE GENERATE A CUSTOM FORMATTED TIMESTAMP USING %%DATE%% AND %%TIME%% COMMANDS

:: --- CHANGE THE COMPUTER DATE FORMAT TEMPORARILY TO MY PREFERENCE "yyyy_MM_dd",
REG COPY "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f 2>nul >nul
REG ADD "HKCU\Control Panel\International" /v sShortDate /d "yyyy_MM_dd" /f 2>nul >nul
SET MYDATE=%date%
:: --- REVERT COMPUTER DATE BACK TO SYSTEM PREFERENCE
REG COPY "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f 2>nul >nul
REG DELETE "HKCU\Control Panel\International-Temp" /f 2>nul >nul

:: --- SPLIT THE TIME DIGITS TO THREE BLOCKS [H] [MM] [SS.SS]
FOR /F "tokens=1-3 delims=:" %%A IN ('echo %time%') DO SET HOUR=%%A& SET MINUTES=%%B& SET SECONDS=%%C

:: --- YOUR CHOICE - FOR 4 DIGIT SECONDS - REMOVES THE DOT FROM THE SECONDS BLOCK [SS.SS]
:: SET SECONDS=%SECONDS:.=%
:: --- YOUR CHOICE - FOR 2 DIGIT SECONDS - GETS THE FIRST TWO DIGITS FROM THE SECONDS BLOCK [SS.SS]
SET SECONDS=%SECONDS:~0,2%

:: --- GET THE "AM PM" STRING TO CHECK THE HOUR BLOCK
FOR /F "tokens=1,2 delims= " %%A IN ('time /t') DO SET AM_PM=%%B  

:: --- CONVERT THE HOUR BLOCK [H] TO "24 HOUR" FORMAT [HH]
IF %AM_PM%==PM (
IF %HOUR%==01 (SET HOUR=13)
IF %HOUR%==02 (SET HOUR=14)
IF %HOUR%==03 (SET HOUR=15)
IF %HOUR%==04 (SET HOUR=16)
IF %HOUR%==05 (SET HOUR=17)
IF %HOUR%==06 (SET HOUR=18)
IF %HOUR%==07 (SET HOUR=19)
IF %HOUR%==08 (SET HOUR=20)
IF %HOUR%==09 (SET HOUR=21)
IF %HOUR%==10 (SET HOUR=22)
IF %HOUR%==11 (SET HOUR=23)
) ELSE (
IF %HOUR%==12 (SET HOUR=00)
IF %HOUR%==1 (SET HOUR=01)
IF %HOUR%==2 (SET HOUR=02)
IF %HOUR%==3 (SET HOUR=03)
IF %HOUR%==4 (SET HOUR=04)
IF %HOUR%==5 (SET HOUR=05)
IF %HOUR%==6 (SET HOUR=06)
IF %HOUR%==7 (SET HOUR=07)
IF %HOUR%==8 (SET HOUR=08)
IF %HOUR%==9 (SET HOUR=09)
)

:: --- GENERATE OUR WANTED TIMESTAMP
ECHO. & ECHO.
SET TIMESTAMP=%MYDATE%__%HOUR%_%MINUTES%_%SECONDS%
ECHO    Your timestamp is:    %TIMESTAMP%

:: --- WAIT - VIEW THE RESULT IN THE CONSOLE SCREEN
ECHO. & ECHO.
ECHO    Job is done. Press any key to exit . . .
PAUSE > NUL

EXIT
 2
Author: derty2,
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
2015-01-14 13:51:33

Este archivo bat (guardar como datetimestr.bat) produce la cadena datetime 3 veces: (1) cadena datetime larga con día de la semana y segundos, (2) cadena de fecha y hora corta sin ellos y (3) versión corta del código.

@echo off
REM "%date: =0%" replaces spaces with zeros
set d=%date: =0%
REM "set yyyy=%d:~-4%" pulls the last 4 characters
set yyyy=%d:~-4%
set mm=%d:~4,2%
set dd=%d:~7,2%
set dow=%d:~0,3%
set d=%yyyy%-%mm%-%dd%_%dow%

set t=%TIME: =0%
REM "%t::=%" removes semi-colons
REM Instead of above, you could use "%t::=-%" to 
REM replace semi-colons with hyphens (or any 
REM non-special character)
set t=%t::=%
set t=%t:.=%

set datetimestr=%d%_%t%
@echo  Long date time str = %datetimestr%

set d=%d:~0,10%
set t=%t:~0,4%
set datetimestr=%d%_%t%
@echo Short date time str = %datetimestr%


@REM Short version of the code above
set d=%date: =0%
set t=%TIME: =0%
set datetimestr=%d:~-4%-%d:~4,2%-%d:~7,2%_%d:~0,3%_%t:~0,2%%t:~3,2%%t:~6,2%%t:~9,2%
@echo Datetimestr = %datetimestr%

pause

Para dar crédito, fusioné los conceptos de Peter Mortensen (Jun 18 '14 a las 21:02) y opello (Ago 25 '11 a las 14:27).

Puede escribir esto mucho más corto, pero esta versión larga facilita la lectura y comprensión del código.

 2
Author: cadvena,
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-04-21 14:20:57

Me gusta la versión corta en la parte superior de @The lorax, pero para otros ajustes de idioma puede ser ligeramente diferente.

Por ejemplo, en la configuración del idioma alemán (con formato de fecha natural: dd.mm.aaaa) la consulta del mes debe modificarse de 4,2 a 3,2:

@ECHO OFF
: Sets the proper date and time stamp with 24h time for log file naming convention i.e.

SET HOUR=%time:~0,2%
SET dtStamp9=%date:~-4%%date:~3,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2% 
SET dtStamp24=%date:~-4%%date:~3,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%

if "%HOUR:~0,1%" == " " (SET dtStamp=%dtStamp9%) else (SET dtStamp=%dtStamp24%)

ECHO %dtStamp%
: Outputs= 20160727_081040
: (format: YYYYMMDD_HHmmss; e.g.: the date-output of this post timestamp)

PAUSE
 2
Author: webMac,
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-12-20 16:02:19

Soy realmente nuevo en los archivos por lotes y este es mi código!! (No estoy seguro de por qué, pero no pude combinar date /t y time /t juntos y no pude usar %date% y %time% directamente sin una variable...)

@ECHO OFF
set ldt=%date% %time%
echo %ldt%>> logs.txt
EXIT

Se reutiliza de otros (la pregunta era obtener un timedate formateado para usar como nombre de archivo).

 2
Author: Kelly,
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-07-23 19:14:08

Estos son mis 2 centavos por undatetime string. En los sistemas MM DD YYYY cambie la primera y la segunda entrada %DATE:~.

    REM ====================================================================================
    REM CREATE UNIQUE DATETIME STRING FOR ADDING TO FILENAME
    REM ====================================================================================
    REM Can handle dd DDxMMxYYYY and DDxMMxYYYY > CREATES YYYYMMDDHHMMSS (x= any character)
    REM ====================================================================================
    REM CHECK for SHORTDATE dd DDxMMxYYYY 
    IF "%DATE:~0,1%" GTR "3" (
        SET DATETIME=%DATE:~9,4%%DATE:~6,2%%DATE:~3,2%%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
    ) ELSE (
    REM ASSUMES SHORTDATE DDxMMxYYYY
        SET DATETIME=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
        )
    REM CORRECT FOR HOURS BELOW 10
    IF %DATETIME:~8,2% LSS 10 SET DATETIME=%DATETIME:~0,8%0%DATETIME:~9,5%
    ECHO %DATETIME%
 1
Author: Case,
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
2013-04-29 13:45:16

Probé la respuesta aceptada y funciona bastante bien. Desafortunadamente, el formato de hora estadounidense parece ser H: MM: SS.CS, y el 0 faltante en el frente estaba causando problemas de análisis antes de las 10 am. Para superar este obstáculo y también permitir el análisis de la mayoría de los formatos de tiempo del mundo, se me ocurrió esta rutina simple que parece funcionar bastante bien.

:ParseTime
rem The format of %%TIME%% is H:MM:SS.CS or (HH:MM:SS,CS) for example 0:01:23.45 or 23:59:59,99
FOR /F "tokens=1,2,3,4 delims=:.," %%a IN ("%1") DO SET /A "%2=(%%a * 360000) + (%%b * 6000) + (%%c * 100) + %%d"
GOTO :EOF

Lo bueno de esta rutina es que pasas la cadena de tiempo como primer parámetro y el nombre del entorno variable desea contener el tiempo (en centisegundos) como segundo parámetro. Por ejemplo:

CALL :ParseTime %START_TIME% START_CS
CALL :ParseTime %TIME% END_CS
SET /A DURATION=%END_CS% - %START_CS%

(*Chris*)

 1
Author: TheChrisPratt,
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-02-27 18:12:34

Tal vez algo como esto:

@call:DateTime

@for %%? in (
    "Year   :Y"
    "Month  :M"
    "Day    :D"
    "Hour   :H"
    "Minutes:I"
    "Seconds:S"
) do @for /f "tokens=1-2 delims=:" %%# in (%%?) do @for /f "delims=" %%_ in ('echo %%_DT_%%$_%%') do @echo %%# : _DT_%%$_ : %%_

:: OUTPUT
:: Year    : _DT_Y_ : 2014
:: Month   : _DT_M_ : 12
:: Day     : _DT_D_ : 17
:: Hour    : _DT_H_ : 09
:: Minutes : _DT_I_ : 04
:: Seconds : _DT_S_ : 35

@pause>nul

@goto:eof

:DateTime
    @verify errorlevel 2>nul & @wmics Alias /? >nul 2>&1
    @if not errorlevel 1 (
        @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 "_DT_D_=%%a" & set "_DT_H_=%%b" & set "_DT_I_=%%c" & set "_DT_M_=%%d" & set "_DT_S_=%%e" & set "_DT_Y_=%%f" )
    ) else (
        @set "_DT_T_=1234567890 "
    )
    @if errorlevel 1 (
        @for %%? in ("iDate" "sDate" "iTime" "sTime" "F" "Y" "M" "D" "H" "I" "S") do @set "_DT_%%~?_=%%~?"
        @for %%? in ("Date" "Time") do @for /f "skip=2 tokens=1,3" %%a in ('reg query "HKCU\Control Panel\International" /v ?%%~? 2^>nul') do @for /f %%x in ('echo:%%_DT_%%a_%%') do @if "%%x"=="%%a" set "_DT_%%a_=%%b"
        @for /f "tokens=1-3 delims=%_DT_T_%" %%a in ("%time%") do @set "_DT_T_=%%a%%b%%c"
    )
    @if errorlevel 1 (
        @if "%_DT_iDate_%"=="0" (set "_DT_F_=_DT_D_ _DT_Y_ _DT_M_") else if "%_DT_iDate_%"=="1" (set "_DT_F_=_DT_D_ _DT_M_ _DT_Y_") else if "%_DT_iDate_%"=="2" (set "_DT_F_=_DT_Y_ _DT_M_ _DT_D_")
        @for /f "tokens=1-4* delims=%_DT_sDate_%" %%a in ('date/t') do @for /f "tokens=1-3" %%x in ('echo:%%_DT_F_%%') do @set "%%x=%%a" & set "%%y=%%b" & set "%%z=%%c"
        @for /f "tokens=1-3 delims=%_DT_T_%" %%a in ("%time%") do @set "_DT_H_=%%a" & set "_DT_I_=%%b" & set "_DT_S_=%%c"
        @for %%? in ("iDate" "sDate" "iTime" "sTime" "F" "T") do @set "_DT_%%~?_="
    )
    @for %%i in ("Y"                ) do @for /f %%j in ('echo:"%%_DT_%%~i_%%"') do @set /a _DT_%%~i_+=  0 & @for /f %%k in ('echo:"%%_DT_%%~i_:~-4%%"') do @set "_DT_%%~i_=%%~k"
    @for %%i in ("M" "D" "H" "I" "S") do @for /f %%j in ('echo:"%%_DT_%%~i_%%"') do @set /a _DT_%%~i_+=100 & @for /f %%k in ('echo:"%%_DT_%%~i_:~-2%%"') do @set "_DT_%%~i_=%%~k"
@exit/b
 1
Author: SerGeeK Kasimov,
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-12-17 09:04:35
:: =============================================================
:: Batch file to display Date and Time seprated by undescore.
:: =============================================================
:: Read the system date.
:: =============================================================
@SET MyDate=%DATE%
@SET MyDate=%MyDate:/=:%
@SET MyDate=%MyDate:-=:%
@SET MyDate=%MyDate: =:%
@SET MyDate=%MyDate:\=:%
@SET MyDate=%MyDate::=_%
:: =============================================================
:: Read the system time.
:: =============================================================
@SET MyTime=%TIME%
@SET MyTime=%MyTime: =0%
@SET MyTime=%MyTime:.=:%
@SET MyTime=%MyTime::=_%
:: =============================================================
:: Build the DateTime string.
:: =============================================================
@SET DateTime=%MyDate%_%MyTime%
:: =============================================================
:: Display the Date and Time as it is now.
:: =============================================================
@ECHO MyDate="%MyDate%" MyTime="%MyTime%" DateTime="%DateTime%"
:: =============================================================
:: Wait before close.
:: =============================================================
@PAUSE
:: =============================================================
 0
Author: Christo,
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
2015-03-18 09:07:33

Para una solución muy simple para la fecha numérica para usar en nombres de archivo use el siguiente código:

set month=%date:~4,2%
set day=%date:~7,2%
set curTimestamp=%month%%day%%year%

rem then the you can add a prefix and a file extension easily like this
echo updates%curTimestamp%.txt
 0
Author: Thomas Boomer,
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
2015-05-20 18:22:01

Divida los resultados del comando date por barra diagonal, luego puede mover cada uno de los tokens a las variables apropiadas.

FOR /F "tokens=1-3 delims=/" %%a IN ("%date:~4%") DO (
SET _Month=%%a
SET _Day=%%b
SET _Year=%%c
)
ECHO Month %_Month%
ECHO Day %_Day%
ECHO Year %_Year%
 0
Author: Casey,
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
2015-08-13 00:59:19

Use REG para guardar/modificar/restaurar los valores que sean más útiles para su archivo bat. Este es Windows 7, para otras versiones es posible que necesite un nombre de clave diferente.

reg save    "HKEY_CURRENT_USER\Control Panel\International" _tmp.reg /y
reg add     "HKEY_CURRENT_USER\Control Panel\International" /v sShortDate  /d "yyyy-MM-dd" /f
set file=%DATE%-%TIME: =0%
reg restore "HKEY_CURRENT_USER\Control Panel\International" _tmp.reg
set file=%file::=-%
set file=%file:.=-%
set file
 0
Author: Malcolm,
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-03-23 16:58:31

En situaciones como esta use un enfoque de programación simple y estándar: En lugar de gastar un gran esfuerzo analizando una entidad desconocida, simplemente guarde la configuración actual, restablézcala a un estado conocido, extraiga la información y luego restaure el estado original. Utilice solo los recursos estándar de Windows.

Específicamente, los formatos de fecha y hora se almacenan bajo la clave del registro HKCU \ Panel de control \ International \ en [definición de MS] "valores": "sTimeFormat "y"sShortDate". Reg es la consola editor del registro incluido con todas las versiones de Windows. No se requieren privilegios elevados para modificar la clave HKCU

Prompt $N:$D $T$G

::Save current config to a temporary (unique name) subkey, Exit if copy fails
Set DateTime=
Set ran=%Random%
Reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp%ran%" /f
If ErrorLevel 1 GoTO :EOF

::Reset the date format to your desired output format (take effect immediately)
::Resetting the time format is useless as it only affect subsequent console windows
::Reg add "HKCU\Control Panel\International" /v sTimeFormat /d "HH_mm_ss"   /f
Reg add "HKCU\Control Panel\International" /v sShortDate  /d "yyyy_MM_dd" /f

::Concatenate the time and (reformatted) date strings, replace any embedded blanks with zeros
Set DateTime=%date%__%time:~0,2%_%time:~3,2%_%time:~6,2%
Set DateTime=%DateTime: =0%

::Restore the original config and delete the temp subkey, Exit if restore fails
Reg copy   "HKCU\Control Panel\International-Temp%ran%" "HKCU\Control Panel\International" /f
If ErrorLevel 1 GoTO :EOF
Reg delete "HKCU\Control Panel\International-Temp%ran%" /f

Simple, directo y debería funcionar para todas las regiones.

Por razones que no entiendo, restablecer el valor "sShortDate" tiene efecto inmediatamente en una ventana de consola pero restablecer el valor muy similar "sTimeFormat" no surte efecto hasta que se abra una nueva ventana de consola. Sin embargo, lo único que se puede cambiar es el delimitador - dígitos las posiciones están fijas.Del mismo modo, se supone que el token de tiempo "HH" precede a los ceros iniciales, pero no lo hace. Afortunadamente, las soluciones son fáciles.

 0
Author: ArtK,
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-10-30 12:53:16

Usando % se encontrará con un error de operación hexadecimal cuando el valor de tiempo es 7-9. Para evitar esto, use DelayedExpansion y grabe los valores de tiempo con !min:~1!

Un método alternativo, si tienes PowerShell es llamar a eso:

for /F "usebackq delims=Z" %%i IN (`powershell Get-Date -format u`) do (set server-time=%%i)
 0
Author: Leland,
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-07 07:47:34

Este script utiliza una interfaz WMI a la que se accede a través de la herramienta WMIC, que es una parte integral de Windows desde Windows XP Professional (Home edition también es compatible, pero la herramienta no está instalada de forma predeterminada). El script también implementa una solución alternativa a la herramienta WMIC que falta creando y llamando a un WSH vbscript para acceder a una interfaz WMI y escribir en la salida de la consola la hora con el mismo formato que proporciona la herramienta WMIC.

@ECHO OFF
REM Returns: RETURN
REM Modify:  RETURN, StdOut
REM Required - mandatory: none
REM Required - optionaly: format strings delimited by a space to format an output delimited by predefined delimiter
REM    YYYY = 4-digit year
REM      MM = 2-digit month
REM      DD = 2-digit day
REM      hh = 2-digit hour
REM      mm = 2-digit minute
REM      ss = 2-digit second
REM      ms = 3-digit millisecond

CALL :getTime %*
ECHO %RETURN%
GOTO :EOF


REM SUBROUTINE
REM Returns: RETURN
REM Modify:  RETURN
REM Required - mandatory: none
REM Required - optionaly: format strings delimited by a space to format an output delimited by predefined delimiter
REM    YYYY = 4-digit year
REM      MM = 2-digit month
REM      DD = 2-digit day
REM      hh = 2-digit hour
REM      mm = 2-digit minute
REM      ss = 2-digit second
REM      ms = 3-digit millisecond
:getTime
  SETLOCAL EnableDelayedExpansion
    SET DELIM=-
    WHERE /Q wmic.exe
    IF NOT ERRORLEVEL 1 FOR /F "usebackq skip=1 tokens=*" %%x IN (`wmic.exe os get LocalDateTime`) DO (SET DT=%%x & GOTO getTime_Parse)
    SET _TMP=%TEMP:"=%
    ECHO Wscript.StdOut.WriteLine (GetObject("winmgmts:root\cimv2:Win32_OperatingSystem=@").LocalDateTime)>"%_TMP%\get_time_local-helper.vbs"
    FOR /F "usebackq tokens=*" %%x IN (`cscript //B //NoLogo "%_TMP%\get_time_local-helper.vbs"`) DO (SET DT=%%x & GOTO getTime_Parse)
    :getTime_Parse
      SET _RET=
      IF "%1" EQU "" (
        SET _RET=%DT:~0,4%%DELIM%%DT:~4,2%%DELIM%%DT:~6,2%%DELIM%%DT:~8,2%%DELIM%%DT:~10,2%%DELIM%%DT:~12,2%%DELIM%%DT:~15,3%
      ) ELSE (
        REM Not recognized format strings are ignored during parsing - no error is reported.
       :getTime_ParseLoop
         SET _VAL=
         IF "%1" EQU "YYYY" SET _VAL=%DT:~0,4%
         IF "%1" EQU "MM"   SET _VAL=%DT:~4,2%
         IF "%1" EQU "DD"   SET _VAL=%DT:~6,2%
         IF "%1" EQU "hh"   SET _VAL=%DT:~8,2%
         IF "%1" EQU "mm"   SET _VAL=%DT:~10,2%
         IF "%1" EQU "ss"   SET _VAL=%DT:~12,2%
         IF "%1" EQU "ms"   SET _VAL=%DT:~15,3%
         IF DEFINED _VAL (
           IF DEFINED _RET (
             SET _RET=!_RET!%DELIM%!_VAL!
           ) ELSE (
             SET _RET=!_VAL!
           )
         )
         SHIFT
         IF "%1" NEQ "" GOTO getTime_ParseLoop
      )
  ENDLOCAL & SET RETURN=%_RET%
GOTO :EOF
 0
Author: Petr Matlas,
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-05-23 17:58:04