Windows 批处理:将日期格式化为变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10945572/
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
Windows batch: formatted date into variable
提问by Maksym Polshcha
How do I save the current date in YYYY-MM-DD format into some variable in a Windows .bat file?
如何将 YYYY-MM-DD 格式的当前日期保存到 Windows .bat 文件中的某个变量中?
Unix shell analogue:
Unix shell 模拟:
today=`date +%F`
echo $today
回答by Joey
You can get the current date in a locale-agnostic way using
您可以使用与语言环境无关的方式获取当前日期
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x
Then you can extract the individual parts using substrings:
然后您可以使用子字符串提取各个部分:
set today=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%
Another way, where you get variables that contain the individual parts, would be:
另一种获取包含各个部分的变量的方法是:
for /f %%x in ('wmic path win32_localtime get /format:list ^| findstr "="') do set %%x
set today=%Year%-%Month%-%Day%
Much nicer than fiddling with substrings, at the expense of polluting your variable namespace.
比摆弄子字符串要好得多,代价是污染你的变量命名空间。
If you need UTC instead of local time, the command is more or less the same:
如果您需要 UTC 而不是本地时间,命令大致相同:
for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set %%x
set today=%Year%-%Month%-%Day%
回答by richhallstoke
If you wish to achieve this using standard MS-DOS commands in a batch file then you could use:
如果您希望使用批处理文件中的标准 MS-DOS 命令实现此目的,那么您可以使用:
FOR /F "TOKENS=1 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET dd=%%A
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2,3 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET yyyy=%%C
I'm sure this can be improved upon further but this gives the date into 3 variables for Day (dd), Month (mm) and Year (yyyy). You can then use these later in your batch script as required.
我确信这可以进一步改进,但这将日期分为 3 个变量,分别为日 (dd)、月 (mm) 和年 (yyyy)。然后,您可以稍后根据需要在批处理脚本中使用这些。
SET todaysdate=%yyyy%%mm%%dd%
echo %dd%
echo %mm%
echo %yyyy%
echo %todaysdate%
While I understand an answer has been accepted for this question this alternative method may be appreciated by many looking to achieve this without using the WMI console, so I hope it adds some value to this question.
虽然我知道这个问题的答案已被接受,但许多希望在不使用 WMI 控制台的情况下实现这一目标的人可能会喜欢这种替代方法,因此我希望它为这个问题增加一些价值。
回答by Anup Rav
Use date /T
to find the format on command prompt.
用于date /T
在命令提示符下查找格式。
If the date format is Thu 17/03/2016
use like this:
如果日期格式是这样Thu 17/03/2016
使用的:
set datestr=%date:~10,4%-%date:~7,2%-%date:~4,2%
echo %datestr%
回答by npocmaka
Two more ways that do not depend on the time settings (both taken from How get data/time independent from localization). And both also get the day of the week and none of them requires admin permissions!:
另外两种不依赖于时间设置的方式(均取自How get data/time Independent from localization)。并且两者都可以获得星期几,并且都不需要管理员权限!:
MAKECAB- will work on EVERY Windows system (fast, but creates a small temporary file) (the foxidrive script):
@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
ROBOCOPY- it's not a native command for Windows XPand Windows Server 2003, but it can be downloaded from the Microsoft site. But it is built-in in everything from Windows Vista and above:
@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
And three more ways that uses other Windows script languages. They will give you more flexibility e.g. you can get week of the year, time in milliseconds and so on.
JScript/BATCHhybrid (need to be saved as
.bat
). JScript is available on every system from Windows NTand above, as a part of Windows Script Host(though can be disabled through the registry it's a rare case):@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());
VBScript/BATCHhybrid (Is it possible to embed and execute VBScript within a batch file without using a temporary file?) same case as jscript , but hybridization is not so perfect:
: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- can be installed on every machine that has .NET - download from Microsoft (v1, v2, and v3(only for Windows 7 and above)). Installed by default on everything form Windows 7/Win2008 and above:
C:\> powershell get-date -format "{dd-MMM-yyyy HH:mm}"
Self-compiled jscript.net/batch(I have never seen a Windows machine without .NET so I think this is a pretty portable):
@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"));
LogmanThis cannot get the year and day of the week. It's comparatively slow, also creates a temp file and is based on the time stamps that logman puts on its log files.Will work everything from Windows XP and above. It probably will be never used by anybody - including me - but it is one more way...
@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
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
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/BATCH混合(需要另存为
.bat
)。JScript 在Windows NT及更高版本的每个系统上都可用,作为Windows Script Host的一部分(虽然可以通过注册表禁用,但这种情况很少见):@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());
VBScript/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/Win2008 及更高版本上:
C:\> powershell get-date -format "{dd-MMM-yyyy HH:mm}"
自编译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
More information about the Get-Date function.
回答by aardvarkk
I really liked Joey's method, but I thought I'd expand upon it a bit.
我真的很喜欢乔伊的方法,但我想我会稍微扩展一下。
In this approach, you can run the code multiple times and not worry about the old date value "sticking around" because it's already defined.
在这种方法中,您可以多次运行代码而不必担心旧的日期值“一直存在”,因为它已经定义了。
Each time you run this batch file, it will output an ISO 8601 compatible combined date and time representation.
每次运行此批处理文件时,它都会输出一个 ISO 8601 兼容的组合日期和时间表示。
FOR /F "skip=1" %%D IN ('WMIC OS GET LocalDateTime') DO (SET LIDATE=%%D & GOTO :GOT_LIDATE)
:GOT_LIDATE
SET DATETIME=%LIDATE:~0,4%-%LIDATE:~4,2%-%LIDATE:~6,2%T%LIDATE:~8,2%:%LIDATE:~10,2%:%LIDATE:~12,2%
ECHO %DATETIME%
In this version, you'll have to be careful not to copy/paste the same code to multiple places in the file because that would cause duplicate labels. You could either have a separate label for each copy, or just put this code into its own batch file and call it from your source file wherever necessary.
在此版本中,您必须小心不要将相同的代码复制/粘贴到文件中的多个位置,因为这会导致重复标签。您可以为每个副本设置一个单独的标签,也可以将此代码放入其自己的批处理文件中,并在必要时从源文件中调用它。
回答by ProVi
Just use the %date%
variable:
只需使用%date%
变量:
echo %date%
回答by Mark
As per answer by @ProVi just change to suit the formatting you require
根据@ProVi 的回答,只需更改以适合您需要的格式
echo %DATE:~10,4%-%DATE:~7,2%-%DATE:~4,2% %TIME:~0,2%:%TIME:~3,2%:%TIME:~6,2%
will return
将返回
yyyy-MM-dd hh:mm:ss
2015-09-15 18:36:11
EDITAs per @Jeb comment, whom is correct the above time format will only work if your DATE /T command returns
编辑根据@Jeb 评论,谁是正确的,上述时间格式仅在您的 DATE /T 命令返回时才有效
ddd dd/mm/yyyy
Thu 17/09/2015
It is easy to edit to suit your locale however, by using the indexing of each character in the string returned by the relevant %DATE% environment variable you can extract the parts of the string you need.
很容易编辑以适应您的语言环境,但是,通过使用相关 %DATE% 环境变量返回的字符串中每个字符的索引,您可以提取您需要的字符串部分。
eg. Using %DATE~10,4% would expand the DATE environment variable, and then use only the 4 characters that begin at the 11th (offset 10) character of the expanded result
例如。使用 %DATE~10,4% 将扩展 DATE 环境变量,然后仅使用从扩展结果的第 11 个(偏移 10)字符开始的 4 个字符
For example if using US styled dates then the following applies
例如,如果使用美国风格的日期,则以下适用
ddd mm/dd/yyyy
Thu 09/17/2015
echo %DATE:~10,4%-%DATE:~4,2%-%DATE:~7,2% %TIME:~0,2%:%TIME:~3,2%:%TIME:~6,2%
2015-09-17 18:36:11
回答by Will
I set an environment variable to the value in the numeric format desired by doing this:
通过执行以下操作,我将环境变量设置为所需数字格式的值:
FOR /F "tokens=1,2,3,4 delims=/ " %a IN ('echo %date%') DO set DateRun=%d-%b-%c
回答by user103004
It is possible to use PowerShell and redirect its output to an environment variable by using a loop.
可以使用 PowerShell 并通过使用循环将其输出重定向到环境变量。
From the command line (cmd
):
从命令行 ( cmd
):
for /f "tokens=*" %a in ('powershell get-date -format "{yyyy-MM-dd+HH:mm}"') do set td=%a
echo %td%
2016-25-02+17:25
In a batch file you might escape %a
as %%a
:
在批处理文件中,您可能会转义%a
为%%a
:
for /f "tokens=*" %%a in ('powershell get-date -format "{yyyy-MM-dd+HH:mm}"') do set td=%%a
回答by Bhaskara Arani
Check this one..
检查这个..
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 "MS=%dt:~15,3%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%-%MS%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause