windows 如何在批处理文件中附加日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/864718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append a date in batch files
提问by AngryHacker
I have the following line in a batch file (that runs on an old Windows 2000box):
我在批处理文件中有以下行(在旧的Windows 2000 机器上运行):
7z a QuickBackup.zip *.backup
How do I append the date to the QuickBackup.zip
file. So if I ran the batch file today, ideally, the file would be QuickBackup20090514.zip
.
如何将日期附加到QuickBackup.zip
文件中。因此,如果我今天运行批处理文件,理想情况下,文件将是QuickBackup20090514.zip
.
Is there a way to do this?
有没有办法做到这一点?
回答by Chris
Bernhard's answerneeded some tweaking work for me because the %DATE% environment variable is in a different format (as commented elsewhere). Also, there was a tilde (~) missing.
Bernhard 的回答需要对我进行一些调整工作,因为 %DATE% 环境变量采用不同的格式(如其他地方所述)。此外,还缺少波浪号 (~)。
Instead of:
代替:
set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:0,2%
set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:0,2%
I had to use:
我不得不使用:
set backupFilename=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%
set backupFilename=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%
for the date format:
对于日期格式:
c:\Scripts>echo %DATE%
c:\Scripts>echo %DATE%
Thu 05/14/2009
2009 年 5 月 14 日星期四
回答by Bernhard Hofmann
This will work for the non-US date format (dd/MM/yyyy
):
这适用于非美国日期格式 ( dd/MM/yyyy
):
set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%
7z a QuickBackup%backupFilename%.zip *.backup
回答by Joe
If you know your regional settings won't change you can do it as follows:
如果您知道您的区域设置不会改变,您可以按如下方式进行:
if your short date format is dd/MM/yyyy:
SET MYDATE=%DATE:~3,2%%DATE:~0,2%%DATE:~8,4%
if your short date format is MM/dd/yyyy:
SET MYDATE=%DATE:~0,2%%DATE:~3,2%%DATE:~8,4%
如果您的短日期格式是 dd/MM/yyyy:
SET MYDATE=%DATE:~3,2%%DATE:~0,2%%DATE:~8,4%
如果您的短日期格式是 MM/dd/yyyy:
SET MYDATE=%DATE:~0,2%%DATE:~3,2%%DATE:~8,4%
But there's no general way to do it that's independent of your regional settings.
但是没有通用的方法可以独立于您的区域设置。
I would not recommend relying on regional settings for anything that's going to be used in a production environment.Instead you should consider using another scripting language - PowerShell, VBScript, ...
对于将在生产环境中使用的任何内容,我不建议依赖区域设置。相反,您应该考虑使用另一种脚本语言 - PowerShell、VBScript、...
For example, if you create a VBS file yyyymmdd.vbsin the same directory as your batch file with the following contents:
例如,如果您在与批处理文件相同的目录中创建一个 VBS 文件yyyymmdd.vbs,其内容如下:
' yyyymmdd.vbs - outputs the current date in the format yyyymmdd
Function Pad(Value, PadCharacter, Length)
Pad = Right(String(Length,PadCharacter) & Value, Length)
End Function
Dim Today
Today = Date
WScript.Echo Pad(Year(Today), "0", 4) & Pad(Month(Today), "0", 2) & Pad(Day(Today), "0", 2)
then you will be able to call it from your batch file thus:
那么您将能够从您的批处理文件中调用它,因此:
FOR /F %%i IN ('cscript "%~dp0yyyymmdd.vbs" //Nologo') do SET MYDATE=%%i
echo %MYDATE%
Of course there will eventually come a point where rewriting your batch file in a more powerful scripting language will make more sense than mixing it with VBScript in this way.
当然,最终会出现这样一种情况:用更强大的脚本语言重写批处理文件比以这种方式将它与 VBScript 混合更有意义。
回答by Michael Fitzpatrick
@SETLOCAL ENABLEDELAYEDEXPANSION
@REM Use WMIC to retrieve date and time
@echo off
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 /A SortDate = 10000 * %%F + 100 * %%D + %%A
set YEAR=!SortDate:~0,4!
set MON=!SortDate:~4,2!
set DAY=!SortDate:~6,2!
@REM Add 1000000 so as to force a prepended 0 if hours less than 10
SET /A SortTime = 1000000 + 10000 * %%B + 100 * %%C + %%E
set HOUR=!SortTime:~1,2!
set MIN=!SortTime:~3,2!
set SEC=!SortTime:~5,2!
)
)
@echo on
@echo DATE=%DATE%, TIME=%TIME%
@echo HOUR=!HOUR! MIN=!MIN! SEC=!SEC!
@echo YR=!YEAR! MON=!MON! DAY=!DAY!
@echo DATECODE= '!YEAR!!MON!!DAY!!HOUR!!MIN!'
Output:
输出:
DATE=2015-05-20, TIME= 1:30:38.59
HOUR=01 MIN=30 SEC=38
YR=2015 MON=05 DAY=20
DATECODE= '201505200130'
回答by ShoeLace
You can also access the date via the variable %DATE%
您还可以通过变量访问日期 %DATE%
When testing my system %DATE%
produces ddd dd/mm/yyyy
测试我的系统时%DATE%
产生 ddd dd/mm/yyyy
you can use substring operators to produce the format you desire
您可以使用子字符串运算符来生成您想要的格式
ie. running the following on MON 11/12/2018 with US regional settings
IE。在 MON 11/12/2018 使用美国区域设置运行以下命令
%DATE:~3,3% %DATE:~0,3% %DATE:~7,2%
Will produce an output:
将产生一个输出:
11 Mon 12
the substring arguments are%*variable*:~*startpos*,*numberofchars*%
子串参数是%*variable*:~*startpos*,*numberofchars*%
回答by Exstinctor Dumbulator
This is all awkward and not local settings independent. Do it like this:
这一切都很尴尬,而且与本地设置无关。像这样做:
%CYGWIN_DIR%\bin\date +%%Y%%m%%d_%%H%%M% > date.txt
for /f "delims=" %%a in ('type "date.txt" 2^>NUL') do set datetime=%%a
echo %datetime%
del date.txt
Yes, use Cygwindate and all your problems are gone!
是的,使用Cygwindate,您的所有问题都消失了!
回答by Dmitri Farkov
Sure.
当然。
FOR %%A IN (%Date:/=%) DO SET Today=%%A
7z a QuickBackup%TODAY%.zip *.backup
That is DDMMYYYY format.
即 DDMMYYYY 格式。
Here's YYYYDDMM:
这是 YYYYDDMM:
FOR %%A IN (%Date%) DO (
FOR /F "tokens=1-3 delims=/-" %%B in ("%%~A") DO (
SET Today=%%D%%B%%C
)
)
7z a QuickBackup%TODAY%.zip *.backup
回答by Cade Roux
I've used the environment variables technique covered here: http://cwashington.netreach.net/depo/view.asp?Index=19
我使用了这里介绍的环境变量技术:http: //cwashington.netreach.net/depo/view.asp?Index=19
Here's the code from that site:
这是该网站的代码:
::~~Author~~. Brett Middleton
::~~Email_Address~~. [email protected]
::~~Script_Type~~. nt command line batch
::~~Sub_Type~~. Misc
::~~Keywords~~. environment variables
::~~Comment~~.
::Sets or clears a group of environment variables containing components of the current date extracted from the string returned by the DATE /T command. These variables can be used to name files, control the flow of execution, etc.
::~~Script~~.
@echo off
::-----------------------------------------------------------------------------
:: SetEnvDate1.CMD 6/30/98
::-----------------------------------------------------------------------------
:: Description : Sets or clears a group of environment variables containing
:: : components of the current date extracted from the string
:: : returned by the DATE /T command. These variables can be
:: : used to name files, control the flow of execution, etc.
:: :
:: Requires : Windows NT with command extensions enabled
:: :
:: Tested : Yes, as demonstration
:: :
:: Contact : Brett Middleton <[email protected]>
:: : Animal and Dairy Science Department
:: : University of Georgia, Athens
::-----------------------------------------------------------------------------
:: USAGE
::
:: SetEnvDate1 can be used as a model for coding date/time routines in
:: other scripts, or can be used by itself as a utility that is called
:: from other scripts.
::
:: Run or call SetEnvDate1 without arguments to set the date variables.
:: Variables are set for the day abbreviation (DT_DAY), month number (DT_MM),
:: day number (DT_DD) and four-digit year (DT_YYYY).
::
:: When the variables are no longer needed, clean up the environment by
:: calling the script again with the CLEAR argument. E.g.,
::
:: call SetEnvDate1 clear
::-----------------------------------------------------------------------------
:: NOTES
::
:: A time variable could be added by parsing the string returned by the
:: built-in TIME /T command. This is left as an exercise for the reader. B-)
::
:: This script illustrates the following NT command extensions:
::
:: 1. Use of the extended IF command to do case-insensitive comparisons.
::
:: 2. Use of the extended DATE command.
::
:: 3. Use of the extended FOR command to parse a string returned by a
:: command or program.
::
:: 4. Use of the "()" conditional processing symbols to group commands
:: for conditional execution. All commands between the parens will
:: be executed if the preceeding IF or FOR statement is TRUE.
::-----------------------------------------------------------------------------
if not "%1" == "?" goto chkarg
echo.
echo Sets or clears date/time variables in the command environment.
echo.
echo SetEnvDate1 [clear]
echo.
echo When called without arguments, the variables are created or updated.
echo When called with the CLEAR argument, the variables are deleted.
echo.
goto endit
::-----------------------------------------------------------------------------
:: Check arguments and select SET or CLEAR routine. Unrecognized arguments
:: are ignored and SET is assumed.
::-----------------------------------------------------------------------------
:chkarg
if /I "%1" == "CLEAR" goto clrvar
goto setvar
::-----------------------------------------------------------------------------
:: Set variables for the day abbreviation (DAY), month number (MM),
:: day number (DD) and 4-digit year (YYYY).
::-----------------------------------------------------------------------------
:setvar
for /F "tokens=1-4 delims=/ " %%i IN ('date /t') DO (
set DT_DAY=%%i
set DT_MM=%%j
set DT_DD=%%k
set DT_YYYY=%%l)
goto endit
::-----------------------------------------------------------------------------
:: Clear all variables from the environment.
::-----------------------------------------------------------------------------
:clrvar
for %%v in (DT_DAY DT_MM DT_DD DT_YYYY) do set %%v=
goto endit
:endit
回答by Andre Miller
There is a tech recipe available herethat shows how to format it to MMDDYYYY, you should be able to adapt it for your needs.
有可用的技术配方在这里展示了如何对其进行格式化,以MMDDYYYY,你应该能够适应它为您的需求。
echo on
@REM Seamonkey's quick date batch (MMDDYYYY format)
@REM Setups %date variable
@REM First parses month, day, and year into mm , dd, yyyy formats and then combines to be MMDDYYYY
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%
echo %date%
EDIT: The reason did not work before was because of 'smartquotes' in the original text. I fixed them and the batch file will work if cut & pasted from this page.
编辑:之前不起作用的原因是因为原文中的“smartquotes”。我修复了它们,如果从此页面剪切和粘贴,批处理文件将起作用。
回答by jph
As has been noted, parsing the date and time is only useful if you know the format being used by the current user (eg. MM/dd/yy or dd-MM-yyyy just to name 2). This could be determined, but by the time you do all the stressing and parsing, you will still end up with some situation where there is an unexpected format used, and more tweaks will be be necessary.
如前所述,解析日期和时间只有在您知道当前用户使用的格式时才有用(例如 MM/dd/yy 或 dd-MM-yyyy 只是为了命名 2)。这可以确定,但是当你完成所有的重读和解析时,你仍然会遇到一些使用意外格式的情况,并且需要更多的调整。
You can also use some external program that will return a date slug in your preferred format, but that has disadvantages of needing to distribute the utility program with your script/batch.
您还可以使用一些外部程序,以您喜欢的格式返回日期段,但缺点是需要使用脚本/批处理分发实用程序。
there are also batch tricks using the CMOS clock in a pretty raw way, but that is tooo close to bare wires for most people, and also not always the preferred place to retrieve the date/time.
还有一些以非常原始的方式使用 CMOS 时钟的批处理技巧,但这对大多数人来说太接近裸线了,而且也不总是检索日期/时间的首选位置。
Below is a solution that avoids the above problems. Yes, it introduces some other issues, but for my purposes I found this to be the easiest, clearest, most portable solution for creating a datestamp in .bat files for modern Windows systems. This is just an example, but I think you will see how to modify for other date and/or time formats, etc.
以下是避免上述问题的解决方案。是的,它引入了一些其他问题,但就我而言,我发现这是在现代 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 the following may be needed to be sure cache is clear before using the new setting
reg query "HKCU\Control Panel\International" /v sShortDate
set LogDate=%date%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f