Datetime 如何在批处理文件中按日期时间创建文件夹

Datetime 如何在批处理文件中按日期时间创建文件夹,datetime,batch-file,command-line,command,Datetime,Batch File,Command Line,Command,我正在尝试使用以下代码在批处理文件中按日期时间创建文件夹 @echo off & for /F "tokens=1-4 delims=/ " %%A in ('date/t') do ( set DateDay=%%A set DateMonth=%%B set Date=%%C set DateYear=%%D ) @echo off & for /F "tokens=1-4 delims=/ " %%D in ('time/t')

我正在尝试使用以下代码在批处理文件中按日期时间创建文件夹

@echo off & for /F "tokens=1-4 delims=/ " %%A in ('date/t') do (
 set DateDay=%%A
 set DateMonth=%%B
 set Date=%%C
set DateYear=%%D
)
@echo off & for /F "tokens=1-4 delims=/ " %%D in ('time/t') do (
set DateTime=%%D
)
set CurrentDate=%Date%-%DateMonth%-%DateYear%-0%time:~0,2%.%time:~3,2%.%time:~6,2%
mkdir %CurrentDate%
使用此选项,我得到的文件夹名称为
22-02-2021-010.01.37
但如果时间在1到9小时内,我的文件夹将显示为
22-02-2021-0 9.59.19
0和9中始终有一个空格,1到9小时不显示为01,02,03小时

答案应该是:

22-02-2021-009.59.19
currentdate
中的
替换
0


提示:使用
set“var1=data”
设置值-这可以避免尾随空格引起的问题。在比较中,使用
如果“thing1”==“thing2”…
来避免由
thing1/2中的空格引起的问题

获得此结果的最佳和正确方法是独立于区域
日/月
顺序使用日期,您可以使用
“WMIC os get LocalDateTime”
作为源,因为它是ISO顺序:


@echo关闭
标题获取带有日期和时间的文件名
调用:GetFileNameWithDateTime MyCurrentDate
回显%MyCurrentDate%
MkDir%MyCurrentDate%
暂停和退出
::----------------------------------------------------------------------------------
:GetFileNameWithDateTime
对于('wmic os get localdatetime')中的/f“skip=1”%%x,如果未定义MyDate,请将其设置为“MyDate=%%x”
设置“%1=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%-%MyDate:~8,2%-%MyDate:~10,2%”
退出/B
::----------------------------------------------------------------------------------

如果您希望在任何现代系统上都能工作,并且不管用户或区域设置如何,仍以特定的格式/顺序输出目录名,那么

您可以从以下位置执行此操作:

@For/F“Tokens=1-6 Delims=/:“%%G In(“%SystemRoot%\System32\Robocopy.exe\:./NJH/L^ |%SystemRoot%\System32\find.exe”123“)Do@MD”%%I-%%H-%%G-0%%J.%K.%L”
或者直接从Windows,
cmd.exe

For/F“Tokens=1-6 Delims=/:%G In(“%SystemRoot%\System32\robocy.exe\:./NJH/L^ |%SystemRoot%\System32\find.exe“123”)Do@MD%I-%H-%G-0%J.%K.%L

这对于根据需要获取日期和时间非常有用。我还希望第二秒出现在文件夹中。
set "CurrentDate=%Date%-%DateMonth%-%DateYear%-0%time:~0,2%.%time:~3,2%.%time:~6,2%"
set "CurrentDate=%currentDate: =0%"
mkdir %CurrentDate%