windows - Windows命令行如何获取当前的日期时间, 以恰当格式表示?

我希望有一个.bat文件,压缩目录到存档中,当前日期和时间是名称的一部分,是否有简单的方法可以这样做,独立于机器的区域设置?

到目前为止,我得到了这个,在我的机器上,得到Tue_10_14_2008_230050_91 :


rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%

rem Now use the timestamp by in a new ZIP file name.
"d:Program Files7-Zip7z.exe" a -r Code_%_my_datetime%.zip Code

我可以用这个代码,但它看起来有点笨拙,

时间:

请参见Windows批处理文件(bat )以MMDDYYYY格式获取当前日期,


@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)
echo %mydate%_%mytime%

如果你希望采用24小时格式的时间,则可以用以下命令替换第二行:


For /f"tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

C:> .date. bat
2008-10-14 _0642

如果您希望日期与区域日/月无关,则可以使用"WMIC os get LocalDateTime"作为来源,因为它以ISO顺序排列:


@echo off
for /F"usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]

C:> test.cmd
本地日期为[ 2012-06-19 10:23:47 .048 ]

这里是一个alt.msdos.batch.nt的变体,它可以独立地工作。

把这个放在一个文本文件中,例如getDate.cmd


-----------8<------8<------------ snip -- snip ----------8<-------------
 :: Works on any NT/2k machine independent of regional date settings
 @ECHO off
 SETLOCAL ENABLEEXTENSIONS
 if"%date%A" LSS"A" (set toks=1-3) else (set toks=2-4)
 for /f"tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
 for /f"tokens=%toks% delims=.-/" %%i in ('date/t') do (
 set '%%a'=%%i
 set '%%b'=%%j
 set '%%c'=%%k))
 if %'yy'% LSS 100 set 'yy'=20%'yy'%
 set Today=%'yy'%-%'mm'%-%'dd'% 
 ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%

 ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]

 :EOF
-----------8<------8<------------ snip -- snip ----------8<-------------

我使用这个(非独立区域(英国))


set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%


@echo off
pushd"%temp%"
makecab /D RptFileName=~.rpt /D InfFileName=~.inf /f nul >nul
for /f"tokens=3-7" %%a in ('find /i"makecab"^<~.rpt') do (
 set"current-date=%%e-%%b-%%c"
 set"current-time=%%d"
 set"weekday=%%a"
)
del ~.*
popd
echo %weekday% %current-date% %current-time%
pause

2. ROBOCOPY -它不是Windows xp和win 2003的本机命令,但可以是从microsoft站点下载


 @echo off
setlocal 
for /f"skip=8 tokens=2,3,4,5,6,7,8 delims=:" %%D in ('robocopy /l * /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (
 set"dow=%%D"
 set"month=%%E"
 set"day=%%F"
 set"HH=%%G"
 set"MM=%%H"
 set"SS=%%I"
 set"year=%%J"
)

echo Day of the week: %dow%
echo Day of the month : %day%
echo Month : %month%
echo hour : %HH%
echo minutes : %MM%
echo seconds : %SS%
echo year : %year%
endlocal

以及其他三种使用其他Windows脚本语言的方式。它们将为您提供更大的灵活性,例如,您可以获取一年中的星期几,毫秒数等。


@if (@X)==(@Y) @end /* ---Harmless hybrid line that begins a JScript comment

@echo off
cscript //E:JScript //nologo"%~f0"
exit /b 0
*------------------------------------------------------------------------------*/

function GetCurrentDate() {
 // Today date time which will used to set as default date.
 var todayDate = new Date();
 todayDate = todayDate.getFullYear() +"-" +
 ("0" + (todayDate.getMonth() + 1)).slice(-2) +"-" +
 ("0" + todayDate.getDate()).slice(-2) +"" + ("0" + todayDate.getHours()).slice(-2) +":" +
 ("0" + todayDate.getMinutes()).slice(-2);

 return todayDate;
 }

WScript.Echo(GetCurrentDate()); 

4. VSCRIPT/BATCH混合(是否可以在不使用临时文件的情况下在批处理文件中嵌入和执行VBScript?)与jscript相同,但是混合并不是那么完美:


:sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%System32doskey.exe %windir%System32'.exe >nul
'& echo current date:
'& cscript /nologo /E:vbscript"%~f0"
'& exit /b

'0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
'1 = vbLongDate - Returns date: weekday, monthname, year
'2 = vbShortDate - Returns date: mm/dd/yy
'3 = vbLongTime - Returns time: hh:mm:ss PM/AM
'4 = vbShortTime - Return time: hh:mm

WScript.echo Replace(FormatDateTime(Date,1),",","-") 

5. PowerShell -可以安装在每个具有.net -从:(v1v2v3 (仅适用于win7和上)下载的机器上,默认情况下安装在:/win2008以上:


C:>powershell get-date -format"{dd-MMM-yyyy HH:mm}"

6.自行编译的jscript.net/batch(从未见过没有.net的Windows机器,所以我认为这是一种可移植的工具):


@if (@X)==(@Y) @end /****** silent line that start jscript comment ******

@echo off
::::::::::::::::::::::::::::::::::::
::: compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist"%~n0.exe" goto :skip_compilation

set"frm=%SystemRoot%Microsoft.NETFramework"
:: searching the latest installed .net framework
for /f"tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n"%SystemRoot%Microsoft.NETFrameworkv*"') do (
 if exist"%%vjsc.exe" (
 rem :: the javascript.net compiler
 set"jsc=%%~dpsnfxvjsc.exe"
 goto :break_loop
 )
)
echo jsc.exe not found && exit /b 0
:break_loop


call %jsc% /nologo /out:"%~n0.exe""%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
::: end of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation

"%~n0.exe" 

exit /b 0


****** end of jscript comment ******/
import System;
import System.IO;

var dt=DateTime.Now;
 Console.WriteLine(dt.ToString("yyyy-MM-dd hh:mm:ss"));

7. Logman这无法获得年份和星期几。它相对较慢,还创建了一个临时文件,并基于logman放置在其日志文件上的时间戳记。它将在XP及更高版本中正常工作。


@echo off
setlocal
del /q /f %temp%timestampfile_*

Logman.exe stop ts-CPU 1>nul 2>&1
Logman.exe delete ts-CPU 1>nul 2>&1

Logman.exe create counter ts-CPU -sc 2 -v mmddhhmm -max 250 -c"Processor(_Total)%% Processor Time" -o %temp%timestampfile_ >nul
Logman.exe start ts-CPU 1>nul 2>&1

Logman.exe stop ts-CPU >nul 2>&1
Logman.exe delete ts-CPU >nul 2>&1
for /f"tokens=2 delims=_." %%t in ('dir /b %temp%timestampfile_*^&del /q/f %temp%timestampfile_*') do set timestamp=%%t

echo %timestamp%
echo MM: %timestamp:~0,2%
echo dd: %timestamp:~2,2%
echo hh: %timestamp:~4,2%
echo mm: %timestamp:~6,2%

endlocal
exit /b 0

关于获取日期函数的更多信息

不幸的是,这受区域设置的影响,但可以满足您的要求。


set hour=%time:~0,2%
if"%time:~0,1%"=="" set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%


FOR /F “TOKENS=1* DELIMS= ” %%A IN (’DATE/T’) DO SET CDATE=%%B
FOR /F “TOKENS=1,2 eol=/ DELIMS=/ ” %%A IN (’DATE/T’) DO SET mm=%%B
FOR /F “TOKENS=1,2 DELIMS=/ eol=/” %%A IN (’echo %CDATE%’) DO SET dd=%%B
FOR /F “TOKENS=2,3 DELIMS=/ ” %%A IN (’echo %CDATE%’) DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%


"d:Program Files7-Zip7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip

另一种方式( credit ):


@For /F"tokens=2,3,4 delims=/" %%A in ('Date /t') do @( 
 Set Month=%%A
 Set Day=%%B
 Set Year=%%C
)

@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year%

请使用以下脚本获取命令行中的当前日期:

 
echo %Date:~0,3%day

 

...