批处理命令文件名中的日期和时间

发布于 2024-12-09 03:33:15 字数 592 浏览 2 评论 0原文

我在命令行上使用 WinZip 压缩文件。由于我们每天都会存档,因此我尝试向这些文件添加日期和时间,以便每次都会自动生成一个新文件。

我使用以下命令生成文件名。将其复制粘贴到命令行中,您应该会看到带有日期和时间组件的文件名。

echo Archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.zip

输出

Archive_20111011_ 93609.zip

但是,我的问题是AMPM。 AM 时间戳为我提供了时间 9(带有前导空格),而 10 自然占用了两个空格。

我想我的问题也会延伸到前九天、前九个月等等。

如何解决此问题,以便包含前导零而不是前导空格,以便获得 Archive_20111011_093609.zip

I am compressing files using WinZip on the command line. Since we archive on a daily basis, I am trying to add date and time to these files so that a new one is auto generated every time.

I use the following to generate a file name. Copy paste it to your command line and you should see a filename with a Date and Time component.

echo Archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.zip

Output

Archive_20111011_ 93609.zip

However, my issue is AM vs PM. The AM time stamp gives me time 9 (with a leading blank space) vs. 10 naturally taking up the two spaces.

I guess my issue will extend to the first nine days, first 9 months, etc. as well.

How do I fix this so that leading zeroes are included instead of leading blank spaces so I get Archive_20111011_093609.zip?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

怪我入戏太深 2024-12-16 03:33:15

另一个解决方案:

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I

它会给你(独立于区域设置!):

  20130802203023.304000+120
( YYYYMMDDhhmmss.<milliseconds><always 000>+/-<minutes difference to UTC>  )

从这里开始,很容易:

set datetime=%datetime:~0,8%-%datetime:~8,6%
20130802-203023

对于 Logan 对文件的“日期时间修改”的相同输出格式的请求:

for %%F in (test.txt) do set file=%%~fF
for /f "tokens=2 delims==" %%I in ('wmic datafile where name^="%file:\=\\%" get lastmodified /format:list') do set datetime=%%I
echo %datetime%

它有点复杂,因为它仅适用于完整路径,wmic 期望反斜杠加倍,并且 = 必须转义(第一个。第二个由周围的引号保护)。

Another solution:

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I

It will give you (independent of locale settings!):

  20130802203023.304000+120
( YYYYMMDDhhmmss.<milliseconds><always 000>+/-<minutes difference to UTC>  )

From here, it is easy:

set datetime=%datetime:~0,8%-%datetime:~8,6%
20130802-203023

For Logan's request for the same outputformat for the "date-time modified" of a file:

for %%F in (test.txt) do set file=%%~fF
for /f "tokens=2 delims==" %%I in ('wmic datafile where name^="%file:\=\\%" get lastmodified /format:list') do set datetime=%%I
echo %datetime%

It is a bit more complicated, because it works only with full paths, wmic expects the backslashes to be doubled and the = has to be escaped (the first one. The second one is protected by surrounding quotes).

朦胧时间 2024-12-16 03:33:15

提取小时,查找前导空格,如果找到则替换为零;

set hr=%time:~0,2%
if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
echo Archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.zip

Extract the hour, look for a leading space, if found replace with a zero;

set hr=%time:~0,2%
if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
echo Archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.zip
傲性难收 2024-12-16 03:33:15

你应该搜索;您只需将所有空格替换为零 set hr=%hr: =0%jeb 2011 年 10 月 11 日14:16

所以我这样做了:

set hr=%time:~0,2%
set hr=%hr: =0%

然后在您要格式化的任何字符串中使用 %hr% 来始终获得两位数的小时。

(Jeb 在最受欢迎的答案下的评论对我来说效果最好,也是最简单的。我将其重新发布到此处,以便对未来的用户来说更加明显。)

You should search; you can simply replace all spaces with zero set hr=%hr: =0%jeb Oct 11 '11 at 14:16

So I did:

set hr=%time:~0,2%
set hr=%hr: =0%

Then use %hr% inside whatever string you are formatting to always get a two-digit hour.

(Jeb's comment under the most popular answer worked the best for me and is the simplest. I repost it here to make it more obvious for future users.)

源来凯始玺欢你 2024-12-16 03:33:15

正如 Vicky 已经指出的,%DATE%%TIME% 使用完全(无限)可定制的短日期和时间格式返回当前日期和时间。

一个用户可以将其系统配置为返回 Fri040811 08.03PM,而另一用户可以选择 08/04/2011 20:30。

对于BAT程序员来说这完全是一场噩梦。

将格式更改为固定格式可能会解决问题,前提是您在保留 BAT 文件之前恢复到以前的格式。但它可能会受到恶劣的竞争条件的影响,并且使已取消的 BAT 文件的恢复变得复杂。

幸运的是,还有一个替代方案。

您可以改用 WMIC。 WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table 以不变的方式返回日期和时间。用FOR /F命令直接解析非常方便。

因此,将各个部分放在一起,尝试以此作为起点......

SETLOCAL enabledelayedexpansion
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
  SET /A FD=%%F*1000000+%%D*100+%%A
  SET /A FT=10000+%%B*100+%%C
  SET FT=!FT:~-4!
  ECHO Archive_!FD!_!FT!.zip
 )

As Vicky already pointed out, %DATE% and %TIME% return the current date and time using the short date and time formats that are fully (endlessly) customizable.

One user may configure its system to return Fri040811 08.03PM while another user may choose 08/04/2011 20:30.

It's a complete nightmare for a BAT programmer.

Changing the format to a firm format may fix the problem, provided you restore back the previous format before leaving the BAT file. But it may be subject to nasty race conditions and complicate recovery in cancelled BAT files.

Fortunately, there is an alternative.

You may use WMIC, instead. WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table returns the date and time in a invariable way. Very convenient to directly parse it with a FOR /F command.

So, putting the pieces together, try this as a starting point...

SETLOCAL enabledelayedexpansion
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
  SET /A FD=%%F*1000000+%%D*100+%%A
  SET /A FT=10000+%%B*100+%%C
  SET FT=!FT:~-4!
  ECHO Archive_!FD!_!FT!.zip
 )
舟遥客 2024-12-16 03:33:15

在阅读了您的所有答案后,我找到了最适合我的解决方案:

set t=%date%_%time%
set d=%t:~10,4%%t:~7,2%%t:~4,2%_%t:~15,2%%t:~18,2%%t:~21,2%
echo hello>"Archive_%d%"

如果是 AM,我会得到 20160915_ 150101 (带有领先的空间和时间)。

如果PM我得到20160915_2150101

I found the best solution for me, after reading all your answers:

set t=%date%_%time%
set d=%t:~10,4%%t:~7,2%%t:~4,2%_%t:~15,2%%t:~18,2%%t:~21,2%
echo hello>"Archive_%d%"

If AM I get 20160915_ 150101 (with a leading space and time).

If PM I get 20160915_2150101.

咿呀咿呀哟 2024-12-16 03:33:15
@For /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do @(

Set DayW=%%A

Set Day=%%B

Set Month=%%C


Set Year=%%D


Set All=%%D%%B%%C
)
"C:\Windows\CWBZIP.EXE" "c:\transfer\ziptest%All%.zip" "C:\transfer\MB5L.txt"

如果在 2012 年 2 月 4 日运行,则需要 MB5L.txt 并将其压缩为 ziptest20120204.zip

@For /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do @(

Set DayW=%%A

Set Day=%%B

Set Month=%%C


Set Year=%%D


Set All=%%D%%B%%C
)
"C:\Windows\CWBZIP.EXE" "c:\transfer\ziptest%All%.zip" "C:\transfer\MB5L.txt"

This takes MB5L.txt and compresses it to ziptest20120204.zip if run on 4 Feb 2012

再可℃爱ぅ一点好了 2024-12-16 03:33:15

您可以批量向变量添加前导零(值最多 99),如下所示:
IF 1%Var% LSS 100 SET Var=0%Var%

因此,您需要将日期和时间组件解析为单独的变量,像这样对待它们,然后将它们连接在一起以创建文件名。

但是,解析日期和时间的基本方法取决于系统区域设置。如果您对代码不能移植到其他机器感到高兴,那可能没问题,但如果您希望它在不同的国际环境中工作,那么您将需要不同的方法,例如通过读出注册表设置

HKEY_CURRENT_USER\Control Panel\International\iDate
HKEY_CURRENT_USER\Control Panel\International\iTime
HKEY_CURRENT_USER\Control Panel\International\iTLZero

:(最后一个控制时间是否有前导零,但据我所知,日期没有前导零)。

You can add leading zeroes to a variable (value up to 99) like this in batch:
IF 1%Var% LSS 100 SET Var=0%Var%

So you'd need to parse your date and time components out into separate variables, treat them all like this, then concatenate them back together to create the file name.

However, your underlying method for parsing date and time is dependent on system locale settings. If you're happy for your code not to be portable to other machines, that's probably fine, but if you expect it to work in different international contexts then you'll need a different approach, for example by reading out the registry settings:

HKEY_CURRENT_USER\Control Panel\International\iDate
HKEY_CURRENT_USER\Control Panel\International\iTime
HKEY_CURRENT_USER\Control Panel\International\iTLZero

(That last one controls whether there is a leading zero on times, but not dates as far as I know).

似最初 2024-12-16 03:33:15

从上面的答案来看,我已经制作了一个可以使用的函数。

使用法国本地设置进行验证。

:::::::: PROGRAM ::::::::::

call:genname "my file 1.txt"
echo "%newname%"
call:genname "my file 2.doc"
echo "%newname%"

echo.&pause&goto:eof
:::::::: FUNCTIONS :::::::::

:genname
    set d1=%date:~-4,4%
    set d2=%date:~-10,2%
    set d3=%date:~-7,2%
    set t1=%time:~0,2%
    ::if "%t1:~0,1%" equ " " set t1=0%t1:~1,1%
    set t1=%t1: =0%
    set t2=%time:~3,2%
    set t3=%time:~6,2%
    set filename=%~1
    set newname=%d1%%d2%%d3%_%t1%%t2%%t3%-%filename%
goto:eof

From the answer above, I have made a ready-to-use function.

Validated with french local settings.

:::::::: PROGRAM ::::::::::

call:genname "my file 1.txt"
echo "%newname%"
call:genname "my file 2.doc"
echo "%newname%"

echo.&pause&goto:eof
:::::::: FUNCTIONS :::::::::

:genname
    set d1=%date:~-4,4%
    set d2=%date:~-10,2%
    set d3=%date:~-7,2%
    set t1=%time:~0,2%
    ::if "%t1:~0,1%" equ " " set t1=0%t1:~1,1%
    set t1=%t1: =0%
    set t2=%time:~3,2%
    set t3=%time:~6,2%
    set filename=%~1
    set newname=%d1%%d2%%d3%_%t1%%t2%%t3%-%filename%
goto:eof
梦年海沫深 2024-12-16 03:33:15

正如其他人已经指出的那样, %DATE%%TIME% 的日期和时间格式(以及 date /T 和 < code>time /T) 依赖于语言环境,因此提取当前日期和时间始终是一场噩梦,并且不可能获得适用于所有可能格式的解决方案,因为几乎没有任何格式限制。


但是像下面这样的代码还有另一个问题(让我们假设日期格式如 MM/DD/YYYY 和 12 h 时间格式如 h:mm:ss.ff ap 其中 apAMPMff 是小数秒):

rem // Resolve AM/PM time:
set "HOUR=%TIME:~,2%"
if "%TIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%TIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %DATE:~-4,4%%DATE:~0,2%%DATE:~3,2%_%HOUR:~-2%%TIME:~3,2%%TIME:~6,2%

每个实例%DATE%%TIME% 返回展开时存在的日期或时间值,因此第一个 %DATE%%TIME% 表达式可能返回与以下值不同的值(您可以证明,当回显包含大量此类表达式(最好是 %TIME%)的长字符串时)。

您可以改进上述代码以保存 %DATE%%TIME% 的单个实例,如下所示:

rem // Store current date and time once in the same line:
set "CURRDATE=%DATE%" & set "CURRTIME=%TIME%"
rem // Resolve AM/PM time:
set "HOUR=%CURRTIME:~,2%"
if "%CURRTIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%CURRTIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %CURRDATE:~-4,4%%CURRDATE:~0,2%%CURRDATE:~3,2%_%HOUR:~-2%%CURRTIME:~3,2%%CURRTIME:~6,2%

但是,%DATE%< 中的返回值仍然如此 : /code> 和 %TIME% 在午夜执行时可以反映不同的日期。

%CURRDATE%%CURRTIME% 中拥有同一天的唯一方法是:

rem // Store current date and time once in the same line:
set "CURRDATE=%DATE%" & set "CURRTIME=%TIME%"
rem // Resolve AM/PM time:
set "HOUR=%CURRTIME:~,2%"
if "%CURRTIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%CURRTIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Fix date/time midnight discrepancy:
if not "%CURRDATE%" == "%DATE%" if %CURRTIME:~0,2% equ 0 set "CURRDATE=%DATE%"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %CURRDATE:~-4,4%%CURRDATE:~0,2%%CURRDATE:~3,2%_%HOUR:~-2%%CURRTIME:~3,2%%CURRTIME:~6,2%

当然,所描述的问题发生的可能性很小,但在某一时刻它会发生并导致奇怪的无法解释的故障。


使用基于 wmic 命令的方法不会出现所描述的问题,如用户答案中所述a href="https://stackoverflow.com/users/2152082" title="Stephan">Stephan 和答案< /a> 按用户PA.,所以我强烈建议选择其中之一。 wmic 的唯一缺点是速度慢得多。

As others have already pointed out, the date and time formats of %DATE% and %TIME% (as well as date /T and time /T) are locale-dependent, so extracting the current date and time is always a nightmare, and it is impossible to get a solution that works with all possible formats since there are hardly any format limitations.


But there is another problem with a code like the following one (let us assume a date format like MM/DD/YYYY and a 12 h time format like h:mm:ss.ff ap where ap is either AM or PM and ff are fractional seconds):

rem // Resolve AM/PM time:
set "HOUR=%TIME:~,2%"
if "%TIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%TIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %DATE:~-4,4%%DATE:~0,2%%DATE:~3,2%_%HOUR:~-2%%TIME:~3,2%%TIME:~6,2%

Each instance of %DATE% and %TIME% returns the date or time value present at the time of its expansion, therefore the first %DATE% or %TIME% expression might return a different value than the following ones (you can prove that when echoing a long string containing a huge amount of such, preferrably %TIME%, expressions).

You could improve the aforementioned code to hold a single instance of %DATE% and %TIME% like this:

rem // Store current date and time once in the same line:
set "CURRDATE=%DATE%" & set "CURRTIME=%TIME%"
rem // Resolve AM/PM time:
set "HOUR=%CURRTIME:~,2%"
if "%CURRTIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%CURRTIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %CURRDATE:~-4,4%%CURRDATE:~0,2%%CURRDATE:~3,2%_%HOUR:~-2%%CURRTIME:~3,2%%CURRTIME:~6,2%

But still, the returned values in %DATE% and %TIME% could reflect different days when executed at midnight.

The only way to have the same day in %CURRDATE% and %CURRTIME% is this:

rem // Store current date and time once in the same line:
set "CURRDATE=%DATE%" & set "CURRTIME=%TIME%"
rem // Resolve AM/PM time:
set "HOUR=%CURRTIME:~,2%"
if "%CURRTIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%CURRTIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Fix date/time midnight discrepancy:
if not "%CURRDATE%" == "%DATE%" if %CURRTIME:~0,2% equ 0 set "CURRDATE=%DATE%"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %CURRDATE:~-4,4%%CURRDATE:~0,2%%CURRDATE:~3,2%_%HOUR:~-2%%CURRTIME:~3,2%%CURRTIME:~6,2%

Of course the occurrence of the described problem is quite improbable, but at one point it will happen and cause strange unexplainable failures.


The described problem cannot occur with the approaches based on the wmic command as described in the answer by user Stephan and in the answer by user PA., so I strongly recommend to go for one of them. The only disadvantage of wmic is that it is way slower.

各自安好 2024-12-16 03:33:15

您的问题似乎得到了解决,但是...

我不确定您是否为您的问题采取了正确的解决方案。
我想你每天都会尝试压缩实际的项目代码。

ZIP 和 1980 可能是一个很好的解决方案,但今天您应该使用存储库系统,例如 subversion 或 git 或...,但不是 zip 文件。

好吧,也许我错了。

Your question seems to be solved, but ...

I'm not sure if you take the right solution for your problem.
I suppose you try to compress each day the actual project code.

It's possible with ZIP and 1980 this was a good solution, but today you should use a repository system, like subversion or git or ..., but not a zip-file.

Ok, perhaps it could be that I'm wrong.

那片花海 2024-12-16 03:33:15

我意识到这对OP来说是一个没有实际意义的问题,但我只是酝酿了这个,我为自己的跳出框框思考感到有点自豪。

下载适用于 Windows 的 gawk,网址为 http://gnuwin32.sourceforge.net/packages/gawk.htm ....然后它是一个单行代码,没有所有笨重的 DOS 批处理语法,需要六个 FOR 循环来分割字符串(WTF?这真的是非常糟糕、疯狂和悲伤!……当然,恕我直言)

如果您已经了解 C、C++、Perl 或 Ruby,那么选择 AWK(继承于前两者,并对后两者做出了重大贡献)是众所周知的蛋糕!!!

DOS 批处理命令:

echo %DATE% %TIME% && echo %DATE% %TIME% | gawk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}"

打印:

Tue 04/09/2012 10:40:38.25
20120904-104038

现在这还不是完整的故事...我只是想偷懒,对日志文件的其余部分进行硬编码-name 在 printf 语句中,因为它很简单...但是如果有人知道如何为 AWK 的输出设置 %NOW% 变量(产生“通用”now 函数的内容),那么我会洗耳恭听。


编辑:

在 StackOverflow 上的快速搜索填补了最后一块拼图,Batch 相当于 Bash反引号

因此,这三行 DOS 批处理:

echo %DATE% %TIME% | awk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}" >%temp%\now.txt
set /p now=<%temp%\now.txt
echo %now%

Produce:

20120904-114434

所以现在我可以在我的 SQL Server 安装(2005+)脚本生成的日志文件的名称中包含一个日期时间: 因此

sqlcmd -S .\SQLEXPRESS -d MyDb -e -i MyTSqlCommands.sql >MyTSqlCommands.sql.%now%.log

,我又是一个快乐的露营者了(除了在 Unix 上的生活还是容易得多)。

I realise this is a moot question to the OP, but I just brewed this, and I'm a tad proud of myself for thinking outside the box.

Download gawk for Windows at http://gnuwin32.sourceforge.net/packages/gawk.htm .... Then it's a one liner, without all that clunky DOS batch syntax, where it takes six FOR loops to split the strings (WTF? That's really really BAD MAD AND SAD! ... IMHO of course)

If you already know C, C++, Perl, or Ruby then picking-up AWK (which inherits from the former two, and contributes significantly to the latter two) is a piece of the proverbial CAKE!!!

The DOS Batch command:

echo %DATE% %TIME% && echo %DATE% %TIME% | gawk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}"

Prints:

Tue 04/09/2012 10:40:38.25
20120904-104038

Now that's not quite the full story... I'm just going to be lazy and hard-code the rest of my log-file-name in the printf statement, because it's simple... But if anybody knows how to set a %NOW% variable to AWK's output (yeilding the guts of a "generic" now function) then I'm all ears.


EDIT:

A quick search on Stack Overflow filled in that last piece of the puzzle, Batch equivalent of Bash backticks.

So, these three lines of DOS batch:

echo %DATE% %TIME% | awk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}" >%temp%\now.txt
set /p now=<%temp%\now.txt
echo %now%

Produce:

20120904-114434

So now I can include a datetime in the name of the log-file produced by my SQL Server installation (2005+) script thus:

sqlcmd -S .\SQLEXPRESS -d MyDb -e -i MyTSqlCommands.sql >MyTSqlCommands.sql.%now%.log

And I'm a happy camper again (except life was still SOOOOO much easier on Unix).

望喜 2024-12-16 03:33:15

我倾向于在 Stephan 当前接受的答案上使用它,因为它可以在之后使用命名参数配置时间戳:

for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set %%x

它将提供以下参数:

  • Day
  • DayOfWeek
  • Hour
  • Milliseconds
  • Minute
  • Month
  • Quarter
  • Second
  • WeekInMonth
  • Year

然后您可以像这样配置格式:

SET DATE=%Year%%Month%%Day%

I prever to use this over the current accepted answer from Stephan as it makes it possible to configure the timestamp using named parameters after that:

for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set %%x

It will provide the following parameters:

  • Day
  • DayOfWeek
  • Hour
  • Milliseconds
  • Minute
  • Month
  • Quarter
  • Second
  • WeekInMonth
  • Year

You can then configure your format like so:

SET DATE=%Year%%Month%%Day%

丑疤怪 2024-12-16 03:33:15

因此,您想要生成格式为 YYYYMMDD_hhmmss 的日期。
由于 %date%%time% 格式取决于区域设置,您可能需要更强大的方法来获取格式化日期。

这里有一个选项:

@if (@X)==(@Y) @end /*
    @cscript //E:JScript //nologo "%~f0"
    @exit /b %errorlevel%
@end*/
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) +
    ("0" + todayDate.getSeconds()).slice(-2) ;
WScript.Echo(todayDate);

如果您将脚本保存为 jsdate.bat,您可以将其指定为一个值:

for /f %%a in ('jsdate.bat') do @set "fdate=%%a"
echo %fdate%

或直接从命令提示符:

for /f %a in ('jsdate.bat') do @set "fdate=%a"

或者您可以使用 powershell,这可能是需要较少代码的方式:

for /f %%# in ('powershell Get-Date -Format "yyyyMMdd_HHmmss"') do set "fdate=%%#"

So you want to generate date in format YYYYMMDD_hhmmss.
As %date% and %time% formats are locale dependant you might need more robust ways to get a formatted date.

Here's one option:

@if (@X)==(@Y) @end /*
    @cscript //E:JScript //nologo "%~f0"
    @exit /b %errorlevel%
@end*/
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) +
    ("0" + todayDate.getSeconds()).slice(-2) ;
WScript.Echo(todayDate);

and if you save the script as jsdate.bat you can assign it as a value :

for /f %%a in ('jsdate.bat') do @set "fdate=%%a"
echo %fdate%

or directly from command prompt:

for /f %a in ('jsdate.bat') do @set "fdate=%a"

Or you can use powershell which probably is the way that requires the less code:

for /f %%# in ('powershell Get-Date -Format "yyyyMMdd_HHmmss"') do set "fdate=%%#"
舟遥客 2024-12-16 03:33:15

将其他选项添加到此答案列表中。

您可以用 0 替换空白,例如 echo %time: =0%

但这仍然是相关的,请将该代码移动到好友电脑上的其他随机位置你会得到有趣的输出。因此,您可以合并 powershell 的 Get-Date

for /f "tokens=*" %%i in ('PowerShell -Command "Get-Date -format 'yyyymmdd_HHmmss'"') do echo %%i.zip"

Adding other options to this list of answers.

you could have replaced empty space with a 0 something like echo %time: =0%

but that is still dependent, move that code to a buddy's PC in some other random place and you'll get funny outputs. So you can incorporate powershell's Get-Date:

for /f "tokens=*" %%i in ('PowerShell -Command "Get-Date -format 'yyyymmdd_HHmmss'"') do echo %%i.zip"
心如狂蝶 2024-12-16 03:33:15

文件名中的空格是合法的。如果您将路径和文件名放在引号中,它可能会飞起来。这是我在批处理文件中使用的内容:

svnadmin hotcopy "C:\SourcePath\Folder" "f:\DestPath\Folder%filename%"

%filename% 中是否有空格并不重要。

A space is legal in file names. If you put your path and file name in quotes, it may just fly. Here's what I'm using in a batch file:

svnadmin hotcopy "C:\SourcePath\Folder" "f:\DestPath\Folder%filename%"

It doesn't matter if there are spaces in %filename%.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文