在Windows (Windows XP)批处理脚本中,我需要格式化当前日期和时间,以便以后在文件名等中使用。

这类似于堆栈溢出问题如何在批处理文件中添加日期,但也包含时间。

到目前为止,我有这个:

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%

这使:

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

是否有一种方法可以允许%TIME%中的个位数小时,以便我可以得到以下结果?

2009_07_28__08_36_01

当前回答

一个很好的单行技巧是使用cmd /c echo ^%time^%来避免早期变量展开

cmd /c echo ^%time^% & dir /s somelongcommand & cmd /c echo ^%time^%

其他回答

@ECHO OFF
: Sets the proper date and time stamp with 24Hr Time for log file naming
: convention ('YYYYMMDD_HHMMSS')

: Scrapes the characters out of their expected permissions in the date/time
: environment variables.

: Expects a date format of '____MM_DD_YYYY'
: Expects a time format of 'HH:MM:SS' or ' H:MM:SS'

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

使用REG保存/修改/恢复对您的bat文件最有用的值。这是windows 7,对于其他版本,你可能需要一个不同的键名。

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
for /f "tokens=1-4 delims=/ " %%I in ("%DATE%") do set curdate=%%K_%%J_%%I
for /f "tokens=1-4 delims=:," %%I in ("%TIME: =0%") do set curtime=%%I_%%J_%%K
echo %curdate%__%curtime%

如果您的系统使用另一个替换delims符号(用于切片到%%I,%%J…) 如果您的系统使用另一个D/M/Y订单,也可以编辑curdate

一个很好的单行技巧是使用cmd /c echo ^%time^%来避免早期变量展开

cmd /c echo ^%time^% & dir /s somelongcommand & cmd /c echo ^%time^%

使用%,当时间值为7-9时,您将遇到十六进制操作错误。为了避免这种情况,请使用delayeexpand并使用!min:~1!

如果你有PowerShell,另一个方法是调用它:

for /F "usebackq delims=Z" %%i IN (`powershell Get-Date -format u`) do (set server-time=%%i)