如何以可预测的格式获取批处理文件中的日期?


17

在批处理文件中,我需要从date命令中提取月,日,年。因此,我使用了以下内容,该内容实质上是解析Date命令以将其子字符串提取到变量中的:

set Day=%Date:~3,2%
set Mth=%Date:~0,2%
set Yr=%Date:~6,4%

一切都很好,但是如果我将此批处理文件部署到具有不同区域/国家/地区设置的计算机上,则会失败,因为月,日和年位于不同的位置。

无论日期格式如何,如何提取月,日和年?


1
您绝对限于批处理吗?在VBScript / WSH和/或PowerShell中,这样的事情要简单得多
Adrien

@Adrien,是的,仅限于批处理-这是VS2008构建后步骤的一部分。
AngryHacker

用%date:
〜6,4

Answers:


14

资料来源:http : //ss64.com/nt/syntax-getdate.html

方法2(单cmd)

GetDate.cmd

@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
)
:s_done

:: Pad digits with leading zeros
      Set _mm=%_mm:~-2%
      Set _dd=%_dd:~-2%
      Set _hour=%_hour:~-2%
      Set _minute=%_minute:~-2%

:: Display the date/time in ISO 8601 format:
Set _isodate=%_yyyy%-%_mm%-%_dd% %_hour%:%_minute%
Echo %_isodate%
pause

在此处输入图片说明


方法1(cmd + vb)

GetDate.cmd

@Echo off
For /f %%G in ('cscript /nologo getdate.vbs') do set _dtm=%%G
Set _yyyy=%_dtm:~0,4%
Set _mm=%_dtm:~4,2%
Set _dd=%_dtm:~6,2%
Set _hh=%_dtm:~8,2%
Set _nn=%_dtm:~10,2%
Echo %_yyyy%-%_mm%-%_dd%T%_hh%:%_nn%

getdate.vbs

Dim dt
dt=now
'output format: yyyymmddHHnn
wscript.echo ((year(dt)*100 + month(dt))*100 + day(dt))*10000 + hour(dt)*100 + minute(dt)

1
啊哈,找到语言环境的日期顺序的一种非常简洁的方法。ss64确实具有cmd.exe用户的漂亮社区。
Nicholi

我从您的源链接中都包含了这两个脚本。希望一切
顺利

@nixda没问题,无论用户如何帮助。
Tex Hex

如果您需要保留上面“方法2”中的秒数,则Set _second=00%%K从中提取时要添加秒数,wmic并像其他方法一样填充前导零。
蒂姆·帕尼提

13

Windows XP及更高版本

getDate.cmd

@echo off
for /f "tokens=2 delims==" %%G in ('wmic os get localdatetime /value') do set datetime=%%G

set year=%datetime:~0,4%
set month=%datetime:~4,2%
set day=%datetime:~6,2%

echo %year%/%month%/%day%

输出量

在此处输入图片说明


+1是最简洁的答案。我还建议以ECHO %year%-%month%-%day%ISO和文件系统兼容的格式结尾(更不用说按年-月-日自动排序)。:-)。
Zephan Schroeder

3

我知道这不完全是您要的,但是我date从批处理文件中的命令使用Linux 应用程序的Windows端口,然后将结果分配给变量。

我还没有找到一种仅使用批处理命令可靠地获取日期的方法。


2

将此批处理文件用于YYYY-MM-DD格式。它使用所有最新Windows版本中都应提供的窗口检测工具来获取独立于区域设置的datetime字符串。

保存到路径(例如c:\ windows \ rdate.bat)的批处理文件中,然后使用CALL RDATE.BAT进行访问以设置变量。或者,将代码复制到批处理文件中。

此日期格式适用于文件名和日志记录。它正确排序。logtime变量将日期+时间变量添加为YYYY-MM-DD-HHMMSS,适用于以第二精度记录日志批处理文件活动。

根据需要调整日期(和时间)格式。REM屏幕在生产中回显。每个文本选择中的两个数字是从零开始的字符索引和要复制的字符数,例如,%datetime:〜0.4%从位置0开始采用4个字符的子字符串。

echo off
rem First, get the locality-invariant datetime
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
rem echo %datetime%

rem Build the reverse date string YYYY-MM-DD
set rdate=%datetime:~0,4%-%datetime:~4,2%-%datetime:~6,2%
echo rdate=%rdate%

rem Built a datetime string YYYY-MM-DD-hhmmss
set logtime=%rdate%-%datetime:~8,6% 
echo logtime=%logtime%

1
几乎与and31415的答案相同。这两个脚本都使用wmic os get localdatetime
nixda


0

您是否尝试过使用NET TIME \\%ComputerName%而不是DATE?我认为这NET TIME应该以一致的格式提供数据,而不考虑语言环境。


不,不是。
AngryHacker

有趣的是,我只是尝试过,在AU和US格式之间切换,并且net time始终以m / d / yyyy格式输出。@AngryHacker,用什么设置对您不起作用?
Hydaral

1
我换了法语(比利时语),这给了我2011-07-27。美国给予07/27/2011
AngryHacker

0

感谢Shekhar的帖子,这项工作可以按需进行,并且时间填充为零。

@Echo Off

for /f "tokens=1-5 delims=:" %%d in ("%time%") do set var=%date:~10,4%%date:~4,2%%date:~7,2%-%%d%%e

set datetimestr=%var: =0%

set logfile=LogFile-%datetimestr%.txt

echo %logfile%

输出:LogFile-20151113-0901.txt


-1

这可能不是主题,但这是我为自己的预定备份编写的.bat文件,也来自Visual Studio中的后期构建操作调用。我希望有人会觉得有用。

将以下内容保存到.bat文件中

--------------------------------------------------
**:: The following is Copyright © 2012 ShopNetNuke Corp.  All rights reserved.
::  and released under the GNU General Public License (GPLv3)**

:: The following section retrieves the current date and time and formats it into the '%var%' variable
:: This format always ensures that the Date and Time are fixed length to avoid the situation of
:: having a value of '12/ 1/2012 rather than '12/01/2012'
echo off
for /f "tokens=1-5 delims=:" %%d in ("%time%") do set var=%date:~10,4%-%date:~4,2%-%date:~7,2%-%%d-%%e
set var=%var: =0%
echo Beginning my valuable Backup Set:  Backup--%var%

:: If you wanted to request the user input a filename prefix, 
:: then we would use something similar to this
:: set /p nameprefix= Enter the file name prefix?
:: Get the Current Date and Time
::for /f "tokens=1-5 delims=:" %%d in ("%time%") do set var=%date:~10,4%-%date:~4,2%-%date:~7,2%-%%d-%%e
:: set var=%var: =0%
:: echo Beginning my valuable Backup Set:  Backup--%var%_%nameprefix%

Pause

echo Starting SQL Server Database Backup Job...
:: The following line initiates the Backup job within SqlServer Agent.
:: Change 'MyBackupNameInSqlAgent' to the name of the job you want executed
:: Change the directory paths to those relevant to your current system installation directories
:: SqlAgent will not return a value if the backup action succeed, 
:: however, in the event an error is encountered, it will be echoed onto the screen
"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\sqlcmd.exe" -S SQLSERVERNAME\INSTANCENAME -Q "execute msdb.dbo.sp_start_job @job_name = 'MyBackupNameInSqlAgent'"
:: An error will be returned if the Backup job is not found or has already been triggered by another process

echo Starting My Valuable Source Code Directory Backup...

echo ...backing up files and folders in "C:\Source\MyPreciousProjectDirectory\"...
:: The following line will execute the 7zip command to create a .7z file of the directory named in 'MyPreciousProjectDirectory'
:: and tells it to put the archive in the 'MyPreciousBackupDirectory'.  The compression level will be defined by the 7zip default settings
:: The -p flag tells 7zip to password protect the archive, in this case, I've used the Date/Time portion of the filename as the password
:: remove the '-p%var%' section to remove password protection from the archive
"C:\Program Files\7-Zip\7z.exe" a -t7z C:\MyPreciousBackupDirectory\%var%\MyPreciousProject--%var%.7z -p%var% -mhe C:\Source\MyPreciousProjectDirectory\* 

echo Source Code Directory Backups complete.

echo Archiving Database Backups now...
:: The following line will execute the 7zip command to archive the Database backup.
:: The '*' could be replaced by the actual backup name.
:: The '*' indicates all files of type '.bak'
:: The -p flag tells 7zip to password protect the archive, in this case, again, I've used the Date/Time portion of the filename as the password
:: remove the '-p%var%' section to remove password protection from the archive
"C:\Program Files\7-Zip\7z.exe" a -t7z  C:\MyPreciousBackupDirectory\%var%\MyPreciousProject-Database-%var%.7z -p%var% -mhe "C:\Program Files\Microsoft SQL Server\MSSQL10.SQLDEV08\MSSQL\Backup\*.bak"

echo Database Backup Archival process complete.

:: If you wanted to place both the previous backups into one single combination archive,
:: you could do something like the following
"C:\Program Files\7-Zip\7z.exe" a -t7z C:\MyPreciousBackupDirectoryForSourceAndDatabase\%var%\MyPreciousProjectBackupSourceAndDatabase--%var%.7z -p%var% -mhe C:\Source\MyPreciousProjectDirectory\* 


echo Now attempting to copy archives to Network Server...
:: The following line will use xcopy to copy the arechives to the server backup directory and place them in a directory named by the DateTime variable %var%
xcopy /S /I /J /Y C:\MyPreciousBackupDirectory\%var% \\MyPreciousBackupServerName\SourceCode\MyPreciousServerBackupDirectory\%var%
:: Or if the combination above was used then copy that...
xcopy /S /I /J /Y C:\MyPreciousBackupDirectoryForSourceAndDatabase\%var% \\MyPreciousBackupServerName\SourceCode\MyPreciousServerBackupDirectory\%var%


echo 7z Archive files transferred to MyPreciousBackupServerName successfully
echo  ||
echo \||/
echo  \/
echo ---------------------------------------------------
echo ----- BACKUP SET "%var%" COMPLETE ------
echo ---------------------------------------------------
pause

1
tl; dr,您可以添加有关脚本功能的说明。因为它不能立即解决。如果您可以删除不相关的代码位,它也可能会更有用
Shekhar 2012年

1
整个批处理脚本都依赖于%date%%time%变量,它们是可识别语言环境的,并且实际上不能按照OP的要求以可预测的方式进行解析。
and31415 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.