在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

Windows中SET命令支持的offset:length格式将不允许您填充您似乎感兴趣的0。

但是,您可以编写一个BATCH脚本来检查小时是否小于10和 相应地用不同的回声字符串进行填充。

您将在此链接中找到关于SET命令的一些信息。


您还可以更改其他编程方法以达到此目的。

在unix bash (Windows上的Cygwin可用)中,只需说,

date +%Y_%m_%d__%H_%M_%S

它总是正确地填充。


以下可能不是一个直接的答案,但一个接近的答案?

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__0%time:~1,2%_%time:~3,2%_%time:~6,2%
else set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%

至少这可能是鼓舞人心的。


我最终得到了这个脚本:

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%

set year=%date:~-4%
echo year=%year%

在WIN2008R2上,例如,我需要使您的'set month=%date:~3,2%'如下所示::否则,00表示month

set month=%date:~4,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
echo month=%month%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
echo day=%day%

set datetimef=%year%%month%%day%_%hour%%min%%secs%

echo datetimef=%datetimef%

@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

REM Assumes UK style date format for date environment variable (DD/MM/YYYY).
REM Assumes times before 10:00:00 (10am) displayed padded with a space instead of a zero.
REM If first character of time is a space (less than 1) then set DATETIME to:
REM YYYY-MM-DD-0h-mm-ss
REM Otherwise, set DATETIME to:
REM YYYY-MM-DD-HH-mm-ss
REM Year, month, day format provides better filename sorting (otherwise, days grouped
REM together when sorted alphabetically).

IF "%time:~0,1%" LSS "1" (
   SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-0%time:~1,1%-%time:~3,2%-%time:~6,2%
) ELSE (
   SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%
)

ECHO %DATETIME%

如前所述,只有在您知道当前用户使用的格式(例如,MM/dd/yy或dd-MM-yyyy,仅举两个例子)时,解析日期和时间才有用。这是可以确定的,但是当您完成所有的强调和解析时,您仍然会遇到使用了意想不到的格式的情况,需要进行更多的调整。

您还可以使用一些外部程序,它们将以您喜欢的格式返回日期段,但这样做的缺点是需要将实用程序与脚本/批处理一起分发。

也有批处理技巧使用CMOS时钟在一个相当原始的方式,但这是太接近裸线对大多数人来说,也不总是首选的地方来检索日期/时间。

下面是避免上述问题的解决方案。是的,它引入了一些其他问题,但就我的目的而言,我发现这是在现代Windows系统的.bat文件中创建日期戳的最简单、最清晰、最可移植的解决方案。这只是一个示例,但我认为您将看到如何修改其他日期和/或时间格式等。

reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f
reg add "HKCU\Control Panel\International" /v sShortDate /d "yyMMdd" /f
@REM reg query "HKCU\Control Panel\International" /v sShortDate
set LogDate=%date%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f

为了生成一个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%)

我今天遇到了这个问题,并解决了它:

SET LOGTIME=%TIME: =0%

它用0代替空格,基本上是零垫小时。

经过一些快速搜索,我没有发现它是否需要命令扩展(仍然使用SETLOCAL DISABLEEXTENSIONS)。


这是我对adatetime字符串的2美分。在MM DD YYYY系统上切换第一个和第二个%DATE:~条目。

    REM ====================================================================================
    REM CREATE UNIQUE DATETIME STRING FOR ADDING TO FILENAME
    REM ====================================================================================
    REM Can handle dd DDxMMxYYYY and DDxMMxYYYY > CREATES YYYYMMDDHHMMSS (x= any character)
    REM ====================================================================================
    REM CHECK for SHORTDATE dd DDxMMxYYYY 
    IF "%DATE:~0,1%" GTR "3" (
        SET DATETIME=%DATE:~9,4%%DATE:~6,2%%DATE:~3,2%%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
    ) ELSE (
    REM ASSUMES SHORTDATE DDxMMxYYYY
        SET DATETIME=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
        )
    REM CORRECT FOR HOURS BELOW 10
    IF %DATETIME:~8,2% LSS 10 SET DATETIME=%DATETIME:~0,8%0%DATETIME:~9,5%
    ECHO %DATETIME%

下面是如何生成一个日志文件名(基于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
...

这个批处理脚本将完全按照O.P.的要求执行(在Windows XP SP3上测试)。

我还使用了前面“jph”所描述的聪明的注册表技巧,我认为这是在任何新的或旧的Windows系统上获得100%一致的日期格式“yyyy_MM_dd”的最简单方法。对一个注册表值的更改是瞬时、临时和微不足道的;它只持续几毫秒,然后立即恢复。

双击此批处理文件进行即时演示,命令提示符窗口将弹出并显示您的时间戳. . . . .

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: generates a custom formatted timestamp string using date and time.
:: run this batch file for an instant demo.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

@ECHO OFF
SETLOCAL & MODE CON:COLS=80 LINES=15 & COLOR 0A

:: --- CHANGE THE COMPUTER DATE FORMAT TEMPORARILY TO MY PREFERENCE "yyyy_MM_dd",
REG COPY "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f 2>nul >nul
REG ADD "HKCU\Control Panel\International" /v sShortDate /d "yyyy_MM_dd" /f 2>nul >nul

SET MYDATE=%date%

:: --- REVERT COMPUTER DATE BACK TO SYSTEM PREFERENCE
REG COPY "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f 2>nul >nul
REG DELETE "HKCU\Control Panel\International-Temp" /f 2>nul >nul

:: --- SPLIT THE TIME [HH:MM:SS.SS] TO THREE SEPARATE VARIABLES [HH] [MM] [SS.SS]
FOR /F "tokens=1-3 delims=:" %%A IN ('echo %time%') DO (
SET HOUR=%%A
SET MINUTES=%%B
SET SECONDS=%%C
)

:: --- CHOOSE ONE OF THESE TWO OPTIONS :
:: --- FOR 4 DIGIT SECONDS        //REMOVES THE DOT FROM THE SECONDS VARIABLE [SS.SS]
:: SET SECONDS=%SECONDS:.=%
:: --- FOR 2 DIGIT SECONDS        //GETS THE FIRST TWO DIGITS FROM THE SECONDS VARIABLE [SS.SS]
SET SECONDS=%SECONDS:~0,2% 

:: --- FROM 12 AM TO 9 AM, THE HOUR VARIABLE WE EXTRACTED FROM %TIME% RETURNS A SINGLE DIGIT, 
:: --- WE PREFIX A ZERO CHARACTER TO THOSE CASES, SO THAT OUR WANTED TIMESTAMP
:: --- ALWAYS GENERATES DOUBLE-DIGIT HOURS (24-HOUR CLOCK TIME SYSTEM).
IF %HOUR%==0 (SET HOUR=00)
IF %HOUR%==1 (SET HOUR=01)
IF %HOUR%==2 (SET HOUR=02)
IF %HOUR%==3 (SET HOUR=03)
IF %HOUR%==4 (SET HOUR=04)
IF %HOUR%==5 (SET HOUR=05)
IF %HOUR%==6 (SET HOUR=06)
IF %HOUR%==7 (SET HOUR=07)
IF %HOUR%==8 (SET HOUR=08)
IF %HOUR%==9 (SET HOUR=09)

:: --- GENERATE OUR WANTED TIMESTAMP
SET TIMESTAMP=%MYDATE%__%HOUR%_%MINUTES%_%SECONDS%

:: --- VIEW THE RESULT IN THE CONSOLE SCREEN
ECHO.
ECHO    Generate a custom formatted timestamp string using date and time.
ECHO.
ECHO    Your timestamp is:    %TIMESTAMP%
ECHO.
ECHO.
ECHO    Job is done. Press any key to exit . . .
PAUSE > NUL

EXIT

如果安装了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上。


我是这样做的:

REM Generate FileName from date and time in format YYYYMMTTHHMM

Time /T > Time.dat
set /P ftime= < Time.dat

set FileName=LogFile%date:~6%%date:~3,2%%date:~0,2%%ftime:~0,2%%ftime:~3,2%.log

echo %FileName%

LogFile201310170928.log


set hourstr = %time:~0,2%
if "%time:~0,1%"==" " (set hourstr=0%time:~1,1%)
set datetimestr=%date:~0,4%%date:~5,2%%date:~8,2%-%hourstr%%time:~3,2%%time:~6,2%

我尝试了公认的答案,效果很好。不幸的是,美国时间格式似乎是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%

克里斯(* *)


创建一个名为“search_files.bat”的文件,并将下面的内容放入该文件中。然后双击它。临时的%THH%变量被放置在适当的位置来处理AM。如果时间的前两位数字为0,Windows将忽略LOG文件的其余文件名。

CD .
SET THH=%time:~0,2%
SET THH=%THH: =0%
dir /s /b *.* > %date:~10,4%-%date:~4,2%-%date:~7,2%@%THH%.%time:~3,2%.%time:~6,2%.LOG

当我需要一个日期/时间字符串时,我通常这样做:

set dt=%DATE:~6,4%_%DATE:~3,2%_%DATE:~0,2%__%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%
set dt=%dt: =0%

这是为德国日期/时间格式(dd.mm。yyyy hh: mm: ss)。基本上,我将子字符串连接起来,最后将所有空格替换为零。

结果字符串的格式为:yyyy_mm_dd__hh_mm_ss


子字符串如何工作的简短解释:

%VARIABLE:~num_chars_to_skip,num_chars_to_keep%

因此,要想从“29.03.2018”这样的日期中得到年份,可以使用:

%DATE:~6,4%
       ^-----skip 6 characters
         ^---keep 4 characters 

我真的是批处理文件的新手,这是我的代码!!(我不知道为什么,但我不能结合日期/t和时间/t在一起,我不能直接使用%date%和%time%没有变量…)

@ECHO OFF
set ldt=%date% %time%
echo %ldt%>> logs.txt
EXIT

它在某种程度上是从其他人那里重用的(问题是获得一个格式化的时间作为文件名)。


也许是这样的:

@call:DateTime

@for %%? in (
    "Year   :Y"
    "Month  :M"
    "Day    :D"
    "Hour   :H"
    "Minutes:I"
    "Seconds:S"
) do @for /f "tokens=1-2 delims=:" %%# in (%%?) do @for /f "delims=" %%_ in ('echo %%_DT_%%$_%%') do @echo %%# : _DT_%%$_ : %%_

:: OUTPUT
:: Year    : _DT_Y_ : 2014
:: Month   : _DT_M_ : 12
:: Day     : _DT_D_ : 17
:: Hour    : _DT_H_ : 09
:: Minutes : _DT_I_ : 04
:: Seconds : _DT_S_ : 35

@pause>nul

@goto:eof

:DateTime
    @verify errorlevel 2>nul & @wmics Alias /? >nul 2>&1
    @if not errorlevel 1 (
        @for /f "skip=1 tokens=1-6" %%a in ('wmic path win32_localtime get day^,hour^,minute^,month^,second^,year /format:table') do @if not "%%f"=="" ( set "_DT_D_=%%a" & set "_DT_H_=%%b" & set "_DT_I_=%%c" & set "_DT_M_=%%d" & set "_DT_S_=%%e" & set "_DT_Y_=%%f" )
    ) else (
        @set "_DT_T_=1234567890 "
    )
    @if errorlevel 1 (
        @for %%? in ("iDate" "sDate" "iTime" "sTime" "F" "Y" "M" "D" "H" "I" "S") do @set "_DT_%%~?_=%%~?"
        @for %%? in ("Date" "Time") do @for /f "skip=2 tokens=1,3" %%a in ('reg query "HKCU\Control Panel\International" /v ?%%~? 2^>nul') do @for /f %%x in ('echo:%%_DT_%%a_%%') do @if "%%x"=="%%a" set "_DT_%%a_=%%b"
        @for /f "tokens=1-3 delims=%_DT_T_%" %%a in ("%time%") do @set "_DT_T_=%%a%%b%%c"
    )
    @if errorlevel 1 (
        @if "%_DT_iDate_%"=="0" (set "_DT_F_=_DT_D_ _DT_Y_ _DT_M_") else if "%_DT_iDate_%"=="1" (set "_DT_F_=_DT_D_ _DT_M_ _DT_Y_") else if "%_DT_iDate_%"=="2" (set "_DT_F_=_DT_Y_ _DT_M_ _DT_D_")
        @for /f "tokens=1-4* delims=%_DT_sDate_%" %%a in ('date/t') do @for /f "tokens=1-3" %%x in ('echo:%%_DT_F_%%') do @set "%%x=%%a" & set "%%y=%%b" & set "%%z=%%c"
        @for /f "tokens=1-3 delims=%_DT_T_%" %%a in ("%time%") do @set "_DT_H_=%%a" & set "_DT_I_=%%b" & set "_DT_S_=%%c"
        @for %%? in ("iDate" "sDate" "iTime" "sTime" "F" "T") do @set "_DT_%%~?_="
    )
    @for %%i in ("Y"                ) do @for /f %%j in ('echo:"%%_DT_%%~i_%%"') do @set /a _DT_%%~i_+=  0 & @for /f %%k in ('echo:"%%_DT_%%~i_:~-4%%"') do @set "_DT_%%~i_=%%~k"
    @for %%i in ("M" "D" "H" "I" "S") do @for /f %%j in ('echo:"%%_DT_%%~i_%%"') do @set /a _DT_%%~i_+=100 & @for /f %%k in ('echo:"%%_DT_%%~i_:~-2%%"') do @set "_DT_%%~i_=%%~k"
@exit/b

:: =============================================================
:: Batch file to display Date and Time seprated by undescore.
:: =============================================================
:: Read the system date.
:: =============================================================
@SET MyDate=%DATE%
@SET MyDate=%MyDate:/=:%
@SET MyDate=%MyDate:-=:%
@SET MyDate=%MyDate: =:%
@SET MyDate=%MyDate:\=:%
@SET MyDate=%MyDate::=_%
:: =============================================================
:: Read the system time.
:: =============================================================
@SET MyTime=%TIME%
@SET MyTime=%MyTime: =0%
@SET MyTime=%MyTime:.=:%
@SET MyTime=%MyTime::=_%
:: =============================================================
:: Build the DateTime string.
:: =============================================================
@SET DateTime=%MyDate%_%MyTime%
:: =============================================================
:: Display the Date and Time as it is now.
:: =============================================================
@ECHO MyDate="%MyDate%" MyTime="%MyTime%" DateTime="%DateTime%"
:: =============================================================
:: Wait before close.
:: =============================================================
@PAUSE
:: =============================================================

用斜杠分隔date命令的结果,然后可以将每个标记移动到适当的变量中。

FOR /F "tokens=1-3 delims=/" %%a IN ("%date:~4%") DO (
SET _Month=%%a
SET _Day=%%b
SET _Year=%%c
)
ECHO Month %_Month%
ECHO Day %_Day%
ECHO Year %_Year%

::========================================================================  
::== CREATE UNIQUE DATETIME STRING IN FORMAT YYYYMMDD-HHMMSS   
::======= ================================================================  
FOR /f %%a IN ('WMIC OS GET LocalDateTime ^| FIND "."') DO SET DTS=%%a  
SET DATETIME=%DTS:~0,8%-%DTS:~8,6%  

第一行输出的格式与时区无关: 20150515150941.077000 + 120 这样,您只需按照自己的愿望格式化输出即可。


为了在文件名中使用数字日期的一个非常简单的解决方案,请使用以下代码:

set month=%date:~4,2%
set day=%date:~7,2%
set curTimestamp=%month%%day%%year%

rem then the you can add a prefix and a file extension easily like this
echo updates%curTimestamp%.txt

如果你不需要这个格式:

2009_07_28__08_36_01

然后你可以使用以下3行代码,使用%date%和%time%:

set mydate=%date:/=%
set mytime=%time::=%
set mytimestamp=%mydate: =_%_%mytime:.=_%

注意:字符/和:被删除,字符。空格被下划线取代。

示例输出(摄于8/5/15星期三下午12:49,时间为50秒93毫秒):

echo %mytimestamp%
Wed_08052015_124950_93

你可以用这些…

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

使用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

这个bat文件(保存为datetimestr.bat)生成3次datetime字符串:(1)长datetime字符串,包含星期几和秒, (2)短的datetime字符串没有它们和 (3)短版代码。

@echo off
REM "%date: =0%" replaces spaces with zeros
set d=%date: =0%
REM "set yyyy=%d:~-4%" pulls the last 4 characters
set yyyy=%d:~-4%
set mm=%d:~4,2%
set dd=%d:~7,2%
set dow=%d:~0,3%
set d=%yyyy%-%mm%-%dd%_%dow%

set t=%TIME: =0%
REM "%t::=%" removes semi-colons
REM Instead of above, you could use "%t::=-%" to 
REM replace semi-colons with hyphens (or any 
REM non-special character)
set t=%t::=%
set t=%t:.=%

set datetimestr=%d%_%t%
@echo  Long date time str = %datetimestr%

set d=%d:~0,10%
set t=%t:~0,4%
set datetimestr=%d%_%t%
@echo Short date time str = %datetimestr%


@REM Short version of the code above
set d=%date: =0%
set t=%TIME: =0%
set datetimestr=%d:~-4%-%d:~4,2%-%d:~7,2%_%d:~0,3%_%t:~0,2%%t:~3,2%%t:~6,2%%t:~9,2%
@echo Datetimestr = %datetimestr%

pause

为了给予适当的赞扬,我将彼得·莫滕森(Peter Mortensen)(14年6月18日21:02)和欧佩罗(opello)(8月25日至11日14:27)的概念融合在一起。

您可以写得更短,但是这个长版本使阅读和理解代码变得更容易。


我喜欢@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

在这种情况下,使用简单、标准的编程方法: 与其花费大量精力解析未知实体,不如简单地保存当前配置,将其重置为已知状态,提取信息,然后恢复原始状态。只使用标准的Windows资源。

具体来说,日期和时间格式存储在注册表项下 HKCU\Control Panel\International\ [MS定义]"values": " timeformat "及"sShortDate"。 Reg是包含在所有Windows版本中的控制台注册表编辑器。 修改HKCU密钥不需要提升权限

Prompt $N:$D $T$G

::Save current config to a temporary (unique name) subkey, Exit if copy fails
Set DateTime=
Set ran=%Random%
Reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp%ran%" /f
If ErrorLevel 1 GoTO :EOF

::Reset the date format to your desired output format (take effect immediately)
::Resetting the time format is useless as it only affect subsequent console windows
::Reg add "HKCU\Control Panel\International" /v sTimeFormat /d "HH_mm_ss"   /f
Reg add "HKCU\Control Panel\International" /v sShortDate  /d "yyyy_MM_dd" /f

::Concatenate the time and (reformatted) date strings, replace any embedded blanks with zeros
Set DateTime=%date%__%time:~0,2%_%time:~3,2%_%time:~6,2%
Set DateTime=%DateTime: =0%

::Restore the original config and delete the temp subkey, Exit if restore fails
Reg copy   "HKCU\Control Panel\International-Temp%ran%" "HKCU\Control Panel\International" /f
If ErrorLevel 1 GoTO :EOF
Reg delete "HKCU\Control Panel\International-Temp%ran%" /f

简单,直接,应该适用于所有地区。

出于我不理解的原因,重置“sShortDate”值立即生效 一个控制台窗口,但重置非常相似的“sTimeFormat”值不会生效 直到打开一个新的控制台窗口。但是,唯一可以更改的是分隔符- 数字的位置是固定的。同样,“HH”时间标记应该在前导零之前,但它没有。 幸运的是,变通方法很简单。


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

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

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

还有另一种简单的方法:

set HH=%time:~0,2%
if %HH% LEQ 9 (
set HH=%time:~1,1%
)

这个脚本使用一个WMI接口,主要通过WMIC工具访问,这是Windows的一个组成部分,因为Windows XP专业版(家庭版也支持,但默认情况下不安装该工具)。该脚本还通过创建和调用WSH vbscript来访问WMI接口,并以与WMIC工具提供的相同格式写入控制台输出时间,从而实现了缺少WMIC工具的解决方案。

@ECHO OFF
REM Returns: RETURN
REM Modify:  RETURN, StdOut
REM Required - mandatory: none
REM Required - optionaly: format strings delimited by a space to format an output delimited by predefined delimiter
REM    YYYY = 4-digit year
REM      MM = 2-digit month
REM      DD = 2-digit day
REM      hh = 2-digit hour
REM      mm = 2-digit minute
REM      ss = 2-digit second
REM      ms = 3-digit millisecond

CALL :getTime %*
ECHO %RETURN%
GOTO :EOF


REM SUBROUTINE
REM Returns: RETURN
REM Modify:  RETURN
REM Required - mandatory: none
REM Required - optionaly: format strings delimited by a space to format an output delimited by predefined delimiter
REM    YYYY = 4-digit year
REM      MM = 2-digit month
REM      DD = 2-digit day
REM      hh = 2-digit hour
REM      mm = 2-digit minute
REM      ss = 2-digit second
REM      ms = 3-digit millisecond
:getTime
  SETLOCAL EnableDelayedExpansion
    SET DELIM=-
    WHERE /Q wmic.exe
    IF NOT ERRORLEVEL 1 FOR /F "usebackq skip=1 tokens=*" %%x IN (`wmic.exe os get LocalDateTime`) DO (SET DT=%%x & GOTO getTime_Parse)
    SET _TMP=%TEMP:"=%
    ECHO Wscript.StdOut.WriteLine (GetObject("winmgmts:root\cimv2:Win32_OperatingSystem=@").LocalDateTime)>"%_TMP%\get_time_local-helper.vbs"
    FOR /F "usebackq tokens=*" %%x IN (`cscript //B //NoLogo "%_TMP%\get_time_local-helper.vbs"`) DO (SET DT=%%x & GOTO getTime_Parse)
    :getTime_Parse
      SET _RET=
      IF "%1" EQU "" (
        SET _RET=%DT:~0,4%%DELIM%%DT:~4,2%%DELIM%%DT:~6,2%%DELIM%%DT:~8,2%%DELIM%%DT:~10,2%%DELIM%%DT:~12,2%%DELIM%%DT:~15,3%
      ) ELSE (
        REM Not recognized format strings are ignored during parsing - no error is reported.
       :getTime_ParseLoop
         SET _VAL=
         IF "%1" EQU "YYYY" SET _VAL=%DT:~0,4%
         IF "%1" EQU "MM"   SET _VAL=%DT:~4,2%
         IF "%1" EQU "DD"   SET _VAL=%DT:~6,2%
         IF "%1" EQU "hh"   SET _VAL=%DT:~8,2%
         IF "%1" EQU "mm"   SET _VAL=%DT:~10,2%
         IF "%1" EQU "ss"   SET _VAL=%DT:~12,2%
         IF "%1" EQU "ms"   SET _VAL=%DT:~15,3%
         IF DEFINED _VAL (
           IF DEFINED _RET (
             SET _RET=!_RET!%DELIM%!_VAL!
           ) ELSE (
             SET _RET=!_VAL!
           )
         )
         SHIFT
         IF "%1" NEQ "" GOTO getTime_ParseLoop
      )
  ENDLOCAL & SET RETURN=%_RET%
GOTO :EOF

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

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

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


希望这能有所帮助:

set MM=%date:~4,2%
set DD=%date:~7,2%
set YYYY=%date:~10,4%

echo %DD%_%MM%_%YYYY%

这将打印05_06_2021


因此,%DATE%的问题在于它依赖于区域设置。所以之前的大部分答案对我来说都不适用。如果你对确切的格式不挑剔,只是想要一个时间戳来区分文件,你可以这样做:

set _date=%DATE%-%TIME%
set _date=%_date:/=-%
set _date=%_date: =-%
set _date=%_date::=-%
set _date=%_date:.=-%
echo %_date%

这应该适用于大多数地区。如果它没有添加另一行,则设置_date=%_date:<offending_char>=-%以删除有问题的字符。例如:一个与文件名不兼容的字符或文件名中不希望出现的字符。

请注意,这并不符合问题所规定的确切标准。


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