更新:现在是2016年我将使用PowerShell,除非它有一个非常引人注目的向后兼容原因,特别是因为使用区域设置问题date
.请参阅@ npocmaka的/sf/ask/17360801/
什么是Windows命令行语句我可以使用以我可以放入文件名的格式获取当前日期时间?
我希望有一个.bat文件,它将目录压缩到一个存档中,并将当前日期和时间作为名称的一部分,例如,Code_2008-10-14_2257.zip
.有没有简单的方法可以做到这一点,独立于机器的区域设置?
我真的不介意日期格式,理想情况下它是yyyy-mm-dd,但任何简单都可以.
到目前为止,我已经有了这个,在我的机器上给了我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 Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code
我可以忍受这个,但它看起来有点笨重.理想情况下,它更简洁,并具有前面提到的格式.
我正在使用Windows Server 2003和Windows XP Professional.我不想安装额外的实用程序来实现这一点(虽然我发现有一些可以做很好的日期格式化).
请参阅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行:
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]
命令的输出格式%DATE%
和dir
区域相关,因此既不健壮也不聪明.date.exe(UnxUtils的一部分)以任何可思考的格式提供任何日期和时间信息.您也可以从任何文件中提取日期/时间信息date.exe
.
date.exe +"%Y-%m-%d"
2009-12-22
date.exe +"%T"
18时55分03秒
date.exe +"%Y%m%d %H%M%S: Any text"
20091222 185503:任何文字
date.exe +"Text: %y/%m/%d-any text-%H.%M"
文字:09/12/22-任何文字-18.55
Command: date.exe +"%m-%d """%H %M %S """"
07-22"18:55:03"`
参考文件中的日期/时间信息:
date.exe -r c:\file.txt +"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S"
在CMD脚本中使用它来获取年,月,日,时间信息:
for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n
在CMD脚本中使用它来获取任何所需格式的时间戳:
for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe +"%%y-%%m-%%d %%H:%%M:%%S"') do set timestamp=%%i
从任何参考文件中提取日期/时间信息.
for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n
向文件添加其日期/时间信息:
for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y-%%m-%%d.%%H%%M%%S"') do ren file.txt file.%%i.txt
date.exe是免费GNU工具的一部分,无需安装.
注意:复制date.exe
到搜索路径中的任何目录可能会导致其他脚本失败,使用Windows内置date
命令.
另外两种不依赖于时间设置的方法(均取自:如何使数据/时间独立于本地化:).而且两者都得到了一周的日子,而且没有一个需要管理员权限!:
MAKECAB - 将在每个Windows系统上工作(快速,但创建一个小的临时文件)(foxidrive脚本):
@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
有关get-date函数的更多信息.
ROBOCOPY - 它不是Windows XP和Windows Server 2003的本机命令,但可以从microsoft站点下载.但是内置在Windows Vista及以上版本的所有内容中:
@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脚本语言的方法.它们将为您提供更多灵活性,例如您可以获得一年中的一周,时间以毫秒为单位等等.
JScript /批处理混合(需要保存为.bat
).JScript在NT及以上版本的每个系统上都可用,作为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());
VSCRIPT/BATCH混合(是否可以在不使用临时文件的情况下在批处理文件中嵌入和执行VBScript?)与JScript相同,但是杂交并不是那么完美:
:sub echo(str) :end sub echo off '>nul 2>&1|| copy /Y %windir%\System32\doskey.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),", ","-")
PowerShell - 可以安装在每台具有.NET的计算机上 - 从Microsoft下载(v1,v2,v3(仅适用于Windows 7及更高版本)).它默认安装在Windows 7/Windows Server 2008及更高版本的所有内容中:
C:\> powershell get-date -format "{dd-MMM-yyyy HH:mm}"
要从批处理文件中使用它:
for /f "delims=" %%# in ('powershell get-date -format "{dd-MMM-yyyy HH:mm}"') do @set _date=%%#
自编的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.NET\Framework\" :: Searching the latest installed .NET framework for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do ( if exist "%%v\jsc.exe" ( rem :: the javascript.net compiler set "jsc=%%~dpsnfxv\jsc.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"));
Logman这不能得到一周中的一年和一天.它相对较慢并且还创建了一个临时文件,它基于logman放在其日志文件上的时间戳.它适用于Windows 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
WMIC还有一种方法,它也提供一年中的一周和一周中的某一天,但不是毫秒(毫秒检查foxidrive的答案):
for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in ("%%#") do @set %%@ echo %day% echo %DayOfWeek% echo %hour% echo %minute% echo %month% echo %quarter% echo %second% echo %weekinmonth% echo %year%
使用TYPEPERF尽快快速兼容不同语言设置并尽快:
@echo off setlocal :: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance ::if defined USERDOMAIN_roamingprofile (set "v=v4") else (set "v=") for /f "tokens=4 delims=. " %%# in ('ver') do if %%# GTR 5 (set "v=v4") else ("v=") set "mon=" for /f "skip=2 delims=," %%# in ('typeperf "\UDP%v%\*" -si 0 -sc 1') do ( if not defined mon ( for /f "tokens=1-7 delims=.:/ " %%a in (%%#) do ( set mon=%%a set date=%%b set year=%%c set hour=%%d set minute=%%e set sec=%%f set ms=%%g ) ) ) echo %year%.%mon%.%date% echo %hour%:%minute%:%sec%.%ms% endlocal
MSHTA允许调用类似于上面#3中演示的JScript方法的JavaScript方法.请记住,涉及月值的JavaScript的Date对象属性编号为0到11,而不是1到12.所以值9表示10月.
这是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<-------------
为了使代码工作没有错误消息到stderr,我不得不为%% a,%% b和%% c的变量赋值添加单引号.我的语言环境(PT)在循环/解析的一个阶段导致错误,其中"set = 20"之类的东西正在执行.引号为赋值语句的左侧产生一个标记(尽管是空的).
缺点是凌乱的语言环境变量名称:'yy','mm'和'dd'.但是,嘿,谁在乎!
我用这个(再次不是地区独立的(英国))
set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%
不幸的是,这不能免受区域设置的影响,但它可以满足您的需求.
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%
你可以在维基百科上找到的东西很棒.
此代码的前四行将为您提供Windows XP Professional及更高版本中可靠的YY DD MM YYYY HH Min Sec变量.
@echo off for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a" set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%" set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%" set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%" echo datestamp: "%datestamp%" echo timestamp: "%timestamp%" echo fullstamp: "%fullstamp%" pause
请使用以下脚本在命令行中获取当天:
echo %Date:~0,3%day
另一种方式(信用):
@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%
请注意,我在这里的答案仍然依赖于区域设置确定的日期和月份的顺序 - 不确定如何解决这个问题.
"d:\Program Files\7-Zip\7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip
这不是真的更简洁,但可能是一种更灵活的方式(信用):
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%
这是一种将日期时间排在一行的方法:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %a in ('%date% %time%') do echo %c-%a-%b %d%e
在美国,这将输出"yyyy-mm-dd hhmm".不同的区域设置将导致不同的%date%输出,但您可以修改令牌顺序.
如果需要不同的格式,请通过重新排列标记或使用不同(或不使用)分隔符来修改echo语句.
简短回答:
:: Start - Run , type: cmd /c "powershell get-date -format ^"{yyyy-MM-dd HH:mm:ss}^"|clip" :: click into target media, Ctrl + V to paste the result
答案很长
@echo off :: START USAGE ================================================================== ::SET THE NICETIME :: SET NICETIME=BOO :: CALL GetNiceTime.cmd :: ECHO NICETIME IS %NICETIME% :: echo nice time is %NICETIME% :: END USAGE ================================================================== echo set hhmmsss :: this is Regional settings dependant so tweak this according your current settings for /f "tokens=1-3 delims=:" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c ::DEBUG ECHO hhmmsss IS %hhmmsss% ::DEBUG PAUSE echo %yyyymmdd% :: this is Regional settings dependant so tweak this according your current settings for /f "tokens=1-3 delims=." %%D in ('echo %DATE%') do set yyyymmdd=%%F%%E%%D ::DEBUG ECHO yyyymmdd IS %yyyymmdd% ::DEBUG PAUSE set NICETIME=%yyyymmdd%_%hhmmsss% ::DEBUG echo THE NICETIME IS %NICETIME% ::DEBUG PAUSE
只需使用此行:
PowerShell -Command "get-date"
我用vMax中的批处理文件更改了答案,因此它也适用于荷兰语.
荷兰-执着,因为我们是-必须在几个变化,以及这打破了原有的批处理文件.%date%
date/t
date
如果有些人可以针对其他Windows语言环境检查这一点,那将会很好,并报告结果.
如果批处理文件在您的位置失败,请在命令提示符下包含这两个语句的输出:
echo:^|date
date/t
这是您应该从批处理文件中获取的输出示例:
C:\temp>set-date-cmd.bat Today is Year: [2011] Month: [01] Day: [03] 20110103
以下是修订后的代码,其中包含以下原因:
:: /sf/ask/17360801/ :: Works on any NT/2k machine independent of regional date settings :: :: 20110103 - adapted by jeroen@pluimers.com for Dutch locale :: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy' :: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date :: set '%%c'=%%k :: set 'yy'=%%k :: :: In addition, date will display the current date before the input prompt using dashes :: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch :: and one occurence in English. :: This skips the first iteration: :: if "%%a" GEQ "A" :: :: echo:^|date :: Huidige datum: ma 03-01-2011 :: Voer de nieuwe datum in: (dd-mm-jj) :: The current date is: Mon 01/03/2011 :: Enter the new date: (mm-dd-yy) :: :: date/t :: ma 03-01-2011 :: Mon 01/03/2011 :: :: The assumption in this batch-file is that echo:^|date will return the date format :: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token. :: :: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens. :: That will resolve the order of the tokens. :: @ECHO off set v_day= set v_month= set v_year= SETLOCAL ENABLEEXTENSIONS if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4) ::DEBUG echo toks=%toks% for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do ( ::DEBUG echo first token=%%a if "%%a" GEQ "A" ( for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do ( set '%%a'=%%i set '%%b'=%%j set 'yy'=%%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%] set datestring=%V_Year%%V_Month%%V_Day% echo %datestring% :EOF
--jeroen
这里是时间部分的类似批处理文件.
:: http://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi :: Works on any NT/2k machine independent of regional time settings :: :: Gets the time in ISO 8601 24-hour format :: :: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that. :: Since ISO 8601 does not care about AM/PM, we use %time% :: @ECHO off SETLOCAL ENABLEEXTENSIONS for /f "tokens=1-4 delims=:,.-/ " %%i in ('echo %time%') do ( set 'hh'=%%i set 'mm'=%%j set 'ss'=%%k set 'ff'=%%l) ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'% ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%] set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction% echo %timestring% :EOF
--jeroen
马修·约翰逊(Matthew Johnson)用于获得单线日期和时间的单线解决方案是雄辩且有用的.
但是,它需要在批处理文件中进行简单的修改:
for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e
基于以下内容的函数wmic
:
:Now -- Gets the current date and time into separate variables :: %~1: [out] Year :: %~2: [out] Month :: %~3: [out] Day :: %~4: [out] Hour :: %~5: [out] Minute :: %~6: [out] Second setlocal for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t endlocal & ( if "%~1" neq "" set %~1=%T:~0,4% if "%~2" neq "" set %~2=%T:~4,2% if "%~3" neq "" set %~3=%T:~6,2% if "%~4" neq "" set %~4=%T:~8,2% if "%~5" neq "" set %~5=%T:~10,2% if "%~6" neq "" set %~6=%T:~12,2% ) goto:eof
上行:区域独立.缺点:只有系统管理员才能运行wmic.exe.
用法:
call:Now Y M D H N S echo %Y%-%M%-%D% %H%:%N%:%S%
这回复了这样一个字符串:
2014-01-22 12:51:53
请注意,函数参数是out-Parameters - 也就是说,您必须提供变量名而不是值.
所有参数都是可选的,call:Now Y M
如果您只想获得年份和月份,那么这是一个有效的通话.
这是我用过的:
::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z") SET DT=%date% SET DT=%DT:/=.% SET DT=%DT:-=.%
如果您想要有关自动备份到7-Zip档案的更多想法,我有一个免费/开放项目,您可以使用或查看想法:http://wittman.org/ziparcy/
我有一个类似的问题。我每天从FTP服务器自动下载一个加密文件。我想使用gpg解密文件,将文件重命名为当前日期(YYYYMMDD格式),然后将解密后的文件放入正确部门的文件夹中。
我经历了一些有关根据日期重命名文件的建议,直到碰巧找到这个简单的解决方案之前,我没有走运。
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt
它运行完美(即文件名显示为“ 2011-06-14.txt”)。
(资源)