在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
下面是如何生成一个日志文件名(基于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
...
我喜欢@The lorax上面的简短版本,
但对于其他语言设置可能略有不同。
例如,在德语设置中(使用自然日期格式:dd.mm.yyyy),月份查询必须从4,2更改为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
你可以用这些…
Parameters:
%date:~4,2% -- month
%date:~7,2% -- days
%date:~10,4% -- years
%time:~1,1% -- hours
%time:~3,2% -- minutes
%time:~6,2% -- seconds
%time:~9,2% -- mili-seconds
%date:~4,2%%date:~7,2%%date:~10,4% : MMDDYYYY
%date:~7,2%%date:~4,2%%date:~10,4% : DDMMYYYY
%date:~10,4%%date:~4,2%%date:~7,2% : YYYYMMDD