使用带有时间戳的批处理脚本创建目录

时间:2015-05-14 06:06:21

标签: windows batch-file

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a-%%b)

set mydir="%mydate%-%mytime%"

mkdir %mydir%

使用上面的批处理脚本,我可以创建一个目录名,如 2015-05-14-11-30 AM

现在我需要将时间转换为24格式并删除AM / PM

预期文件夹名称 - 2015-05-14-11-30

怎么做?

2 个答案:

答案 0 :(得分:3)

我认为你应该使用%TIME%伪变量。

这是一个例子:

@echo off

For /f "tokens=1-4 delims=/:." %%a in ("%TIME%") do (
    SET HH24=%%a
    SET MI=%%b
    SET SS=%%c
    SET FF=%%d
)

For /f "tokens=1-2 delims=/,." %%a in ("%SS%") do (
    SET JUST_SS=%%a
)

echo HH24=%HH24%
echo MI=%MI%
echo SS=%SS%
echo FF=%FF%
echo JUST_SS=%JUST_SS%

echo mytime=%HH24%-%MI%-%JUST_SS%

嗯,如果小时数小于10,我意识到HH24有空格,所以在这里你有另一个解决方案,使用%time

SET HH=%time:~0,2%
if "%HH:~0,1%" == " " SET HH=0%HH:~1,1%
    echo HH=%HH%

SET MI=%time:~3,2%
if "%MI:~0,1%" == " " SET MI=0%MI:~1,1%
    echo MI=%MI%

SET SS=%time:~6,2%
if "%SS:~0,1%" == " " SET SS=0%SS:~1,1%
    echo SS=%SS%

根据@Stephan指出的建议(TIME变量取决于地区设置),我们可以使用这种方法:

@echo off

for /f "delims=" %%a in ('wmic OS get localdatetime  ^| find "."') do set datetime=%%a

set "YYYY=%datetime:~0,4%"
set "MM=%datetime:~4,2%"
set "DD=%datetime:~6,2%"
set "HH=%datetime:~8,2%"
set "MI=%datetime:~10,2%"
set "SS=%datetime:~12,2%"

set fullstamp=%YYYY%-%MM%-%DD%-%HH%-%MI%-%SS%
echo fullstamp=%fullstamp%

答案 1 :(得分:1)

让它变得简单&短

 @echo off

 set hh=%time:~-11,2%
 set /a hh=%hh%+100
 set hh=%hh:~1%
 Set mydir=%date:~10,4%-%date:~4,2%-%date:~7,2%-%hh%-%time:~3,2%-%time:~6,2%
 mkdir %mydir%