在 Windows 批处理脚本中格式化日期和时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1192476/
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
Format date and time in a Windows batch script
提问by laurie
In a Windows (Windows XP) batch script I need to format the current date and time for later use in files names, etc.
在 Windows (Windows XP) 批处理脚本中,我需要格式化当前日期和时间以供以后在文件名等中使用。
It is similar to Stack Overflow question How to append a date in batch files, but with time in as well.
它类似于 Stack Overflow 问题How to append a date in batch files,但也包含时间。
I have this so far:
到目前为止我有这个:
echo %DATE%
echo %TIME%
set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%
echo %datetimef%
which gives:
这使:
28/07/2009
8:35:31.01
2009_07_28__ 8_36_01
Is there a way I can allow for a single digit hour in %TIME%, so I can get the following?
有没有办法可以在 %TIME% 中允许一个位数的小时,以便我可以获得以下内容?
2009_07_28__08_36_01
采纳答案by laurie
I ended up with this script:
我最终得到了这个脚本:
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%
set year=%date:~-4%
echo year=%year%
:: On WIN2008R2 e.g. I needed to make your 'set month=%date:~3,2%' like below ::otherwise 00 appears for MONTH
:: 在 WIN2008R2 上,例如我需要像下面这样设置“设置月份=%日期:~3,2%”::否则 MONTH 出现 00
set month=%date:~4,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
echo month=%month%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
echo day=%day%
set datetimef=%year%%month%%day%_%hour%%min%%secs%
echo datetimef=%datetimef%
回答by laurie
@ECHO OFF
: Sets the proper date and time stamp with 24Hr Time for log file naming
: convention
SET HOUR=%time:~0,2%
SET dtStamp9=%date:~-4%%date:~4,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2%
SET dtStamp24=%date:~-4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%
if "%HOUR:~0,1%" == " " (SET dtStamp=%dtStamp9%) else (SET dtStamp=%dtStamp24%)
ECHO %dtStamp%
PAUSE
回答by nightcoder
Here is how I generate a log filename (based on http://ss64.com/nt/syntax-getdate.html):
这是我生成日志文件名的方法(基于http://ss64.com/nt/syntax-getdate.html):
@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
SET _second=00%%K
)
:s_done
:: Pad digits with leading zeros
Set _mm=%_mm:~-2%
Set _dd=%_dd:~-2%
Set _hour=%_hour:~-2%
Set _minute=%_minute:~-2%
Set _second=%_second:~-2%
Set logtimestamp=%_yyyy%-%_mm%-%_dd%_%_hour%_%_minute%_%_second%
goto make_dump
:s_error
echo WMIC is not available, using default log filename
Set logtimestamp=_
:make_dump
set FILENAME=database_dump_%logtimestamp%.sql
...
回答by Andreas
I usually do it this way whenever I need a date/time string:
每当我需要日期/时间字符串时,我通常会这样做:
set dt=%DATE:~6,4%_%DATE:~3,2%_%DATE:~0,2%__%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%
set dt=%dt: =0%
This is for the German date/time format (dd.mm.yyyy hh:mm:ss). Basically I concatenate the substrings and finally replace all spaces with zeros.
这是针对德国日期/时间格式 (dd.mm.yyyy hh:mm:ss)。基本上我连接子字符串,最后用零替换所有空格。
Short explanation of how substrings work:
子字符串如何工作的简短说明:
%VARIABLE:~num_chars_to_skip,num_chars_to_keep%
So to get just the year from a date like "29.03.2018" use:
因此,要从“29.03.2018”之类的日期中获取年份,请使用:
%DATE:~6,4%
^-----skip 6 characters
^---keep 4 characters
回答by G. Lombard
If PowerShell is installed, then you can easily and reliably get the Date/Time in any format you'd like, for example:
如果安装了 PowerShell,那么您可以轻松可靠地以您喜欢的任何格式获取日期/时间,例如:
for /f %%a in ('powershell -Command "Get-Date -format yyyy_MM_dd__HH_mm_ss"') do set datetime=%%a
move "%oldfile%" "backup-%datetime%"
Of course nowadays PowerShell is always installed, but on Windows XP you'll probably only want to use this technique if your batch script is being used in a known environment where you know PS is available (or check in your batch file if PowerShell is available...)
当然,现在 PowerShell 总是安装的,但在 Windows XP 上,如果您的批处理脚本在已知的环境中使用,并且您知道 PS 可用(或者如果 PowerShell 可用,请检查您的批处理文件),您可能只想使用此技术...)
You may reasonably ask: why use a batch file at all if you can use PowerShell to get the date/time, but I think some obvious reasons are: (a) you're not all that familiar with PowerShell and still prefer to do most things the old-fashioned way with batch files or (b) you're updating an old script and don't want to port the whole thing to PS.
您可能会合理地问:如果您可以使用 PowerShell 获取日期/时间,为什么还要使用批处理文件,但我认为一些明显的原因是:(a) 您对 PowerShell 并不十分熟悉,但仍然更喜欢做大多数事情使用批处理文件的老式方法或 (b) 您正在更新旧脚本并且不想将整个内容移植到 PS。
回答by opello
I came across this problem today and solved it with:
我今天遇到了这个问题并解决了它:
SET LOGTIME=%TIME: =0%
It replaces spaces with 0s and basically zero-pads the hour.
它用 0 替换空格,基本上零填充小时。
After some quick searching I didn't find out if it required command extensions (still worked with SETLOCAL DISABLEEXTENSIONS).
经过一些快速搜索,我没有发现它是否需要命令扩展(仍然使用 SETLOCAL DISABLEEXTENSIONS)。
回答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 (for example, MM/dd/yy or dd-MM-yyyy just to name two). 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 仅举两个例子)。这可以确定,但是当你完成所有的重读和解析时,你仍然会遇到一些使用意外格式的情况,并且需要更多的调整。
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 reg query "HKCU\Control Panel\International" /v sShortDate
set LogDate=%date%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f
回答by ufukgun
The following may not be a direct answer but a close one?
以下可能不是直接的答案而是接近的答案?
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__0%time:~1,2%_%time:~3,2%_%time:~6,2%
else set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%
At least it may be inspiring.
至少它可能是鼓舞人心的。
回答by Jesse
If you don't exactly need this format:
如果您并不完全需要这种格式:
2009_07_28__08_36_01
Then you could use the following 3 lines of codewhich uses %date% and %time%:
然后您可以使用以下3 行代码,它们使用 %date% 和 %time%:
set mydate=%date:/=%
set mytime=%time::=%
set mytimestamp=%mydate: =_%_%mytime:.=_%
Note: The characters /
and :
are removed and the character .
and space is replaced with an underscore.
注意:字符/
和:
被删除,字符.
和空格替换为下划线。
Example output (taken Wednesday 8/5/15 at 12:49 PM with 50 seconds and 93 milliseconds):
示例输出(2015 年 8 月 5 日星期三下午 12:49 拍摄,时间为 50 秒和 93 毫秒):
echo %mytimestamp%
Wed_08052015_124950_93
回答by Mike Raynham
REM Assumes UK style date format for date environment variable (DD/MM/YYYY).
REM Assumes times before 10:00:00 (10am) displayed padded with a space instead of a zero.
REM If first character of time is a space (less than 1) then set DATETIME to:
REM YYYY-MM-DD-0h-mm-ss
REM Otherwise, set DATETIME to:
REM YYYY-MM-DD-HH-mm-ss
REM Year, month, day format provides better filename sorting (otherwise, days grouped
REM together when sorted alphabetically).
IF "%time:~0,1%" LSS "1" (
SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-0%time:~1,1%-%time:~3,2%-%time:~6,2%
) ELSE (
SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%
)
ECHO %DATETIME%