在 Windows 批处理脚本中格式化日期和时间 [英] Format date and time in a Windows batch script
本文介绍了在 Windows 批处理脚本中格式化日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Windows (Windows XP) 批处理脚本中,我需要格式化当前日期和时间以供以后在文件名等中使用.
In a Windows (Windows XP) batch script I need to format the current date and time for later use in files names, etc.
它类似于堆栈溢出问题如何追加批处理文件中的日期,但也包含时间.
It is similar to Stack Overflow question How to append a date in batch files, but with time in as well.
到目前为止我有这个:
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%
给出:
28/07/2009
8:35:31.01
2009_07_28__ 8_36_01
有没有一种方法可以让我在 %TIME% 中允许一个位数的小时,以便我可以得到以下内容?
Is there a way I can allow for a single digit hour in %TIME%, so I can get the following?
2009_07_28__08_36_01
推荐答案
我最终得到了这个脚本:
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%
:: 在 WIN2008R2 上,例如我需要让你的 'set month=%date:~3,2%' 如下所示::否则 00 出现在 MONTH
:: On WIN2008R2 e.g. I needed to make your 'set month=%date:~3,2%' like below ::otherwise 00 appears for MONTH
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%
这篇关于在 Windows 批处理脚本中格式化日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文