在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

当前回答

为了生成一个YYYY-MM-DD hh:mm:ss(24小时)时间戳,我使用:

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

其他回答

如果安装了PowerShell,那么您可以轻松可靠地以任何您想要的格式获取日期/时间,例如:

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

当然,现在总是安装PowerShell,但在Windows XP上,你可能只会想要使用这种技术,如果你的批处理脚本是在一个已知的环境中使用,你知道PS可用(或者检查你的批处理文件,如果PowerShell可用…)

你可能会合理地问:如果你可以使用PowerShell来获取日期/时间,为什么还要使用批处理文件,但我认为一些明显的原因是:(a)你对PowerShell并不熟悉,仍然更喜欢用老式的批处理文件方式来做大多数事情;或者(b)你正在更新一个旧脚本,不想把整个脚本移植到PS上。

@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

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

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

我尝试了公认的答案,效果很好。不幸的是,美国时间格式似乎是H:MM:SS.CS,前面缺少0导致上午10点之前的解析问题。为了克服这个障碍,并允许解析大多数世界时间格式,我提出了这个简单的例程,它似乎工作得相当好。

: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

这个例程的好处是将时间字符串作为第一个参数传入,将希望包含时间(以厘秒为单位)的环境变量名称作为第二个参数传入。例如:

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

克里斯(* *)

设置xtime = % % 如果“%xtime:~0,1%”==“”则设置xtime=0%xtime:~1,7% 设置isodate = %日期:~ -4% %日期:~ 3,2% %日期:~ 0,2% _ % xtime: ~ 0, 2% % xtime: ~ 3, 2% %时间:~ 6 2%