更新:现在是2016年,我将使用PowerShell,除非有一个真正令人信服的向后兼容的原因,特别是因为使用日期的区域设置问题。参见@npocmaka的https://stackoverflow.com/a/19799236/8479


什么是Windows命令行语句(s),我可以使用以我可以放入文件名的格式获取当前日期时间?

我想要一个.bat文件,它将一个目录压缩成一个归档文件,其中当前日期和时间作为名称的一部分,例如Code_2008-10-14_2257.zip。有什么简单的方法可以做到这一点,独立于机器的区域设置吗?

我真的不介意日期格式,理想情况下它是yyyy-mm-dd,但任何简单的都可以。

到目前为止,我已经得到了这个,在我的机器上给我Tue_10_14_2008_230050_91:

rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%

rem Now use the timestamp by in a new ZIP file name.
"d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code

我可以接受这个,但它似乎有点笨重。理想情况下,它应该更简短,并具有前面提到的格式。

我用的是Windows Server 2003和Windows XP Professional。我不想安装额外的实用程序来实现这一点(尽管我知道有一些工具可以很好地格式化日期)。


当前回答

给定一个已知位置,供函数形式参考。ECHOTIMESTAMP调用显示了如何将时间戳转换为变量(本例中为DTS)。

@ECHO off

CALL :ECHOTIMESTAMP
GOTO END

:TIMESTAMP
SETLOCAL  EnableDelayedExpansion
    SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!
    SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!
    SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!
ENDLOCAL & SET "%~1=%DTS%"
GOTO :EOF

:ECHOTIMESTAMP
SETLOCAL
    CALL :TIMESTAMP DTS
    ECHO %DTS%
ENDLOCAL
GOTO :EOF

:END

EXIT /b 0

并保存到文件,timestamp.bat,下面是输出:

其他回答

我用vMax的批处理文件更改了答案,所以它也适用于荷兰语。 荷兰语(尽管我们是持久性的)在%date%、date/t和date中有一些更改,这些更改破坏了原始的批处理文件。

如果有些人也能检查其他Windows locale,并报告结果,那就太好了。 如果批处理文件在您的位置失败,那么请在命令提示符中包含这两个语句的输出: 回音:^ |日期 日期/ t

这是你应该从批处理文件中得到的输出示例:

C:\temp>set-date-cmd.bat
Today is Year: [2011] Month: [01] Day: [03]
20110103

以下是修改后的代码及其原因:

:: https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-usi
:: Works on any NT/2k machine independent of regional date settings
::
:: 20110103 - adapted by jeroen@pluimers.com for Dutch locale
:: Dutch will get jj as year from echo:^|date, so the '%%c' trick does not work as it will fill 'jj', but we want 'yy'
:: luckily, all countries seem to have year at the end: http://en.wikipedia.org/wiki/Calendar_date
::            set '%%c'=%%k
::            set 'yy'=%%k
::
:: In addition, date will display the current date before the input prompt using dashes
:: in Dutch, but using slashes in English, so there will be two occurances of the outer loop in Dutch
:: and one occurence in English.
:: This skips the first iteration:
::        if "%%a" GEQ "A"
::
:: echo:^|date
:: Huidige datum: ma 03-01-2011
:: Voer de nieuwe datum in: (dd-mm-jj)
:: The current date is: Mon 01/03/2011
:: Enter the new date: (mm-dd-yy)
::
:: date/t
:: ma 03-01-2011
:: Mon 01/03/2011
::
:: The assumption in this batch-file is that echo:^|date will return the date format
:: using either mm and dd or dd and mm in the first two valid tokens on the second line, and the year as the last token.
::
:: The outer loop will get the right tokens, the inner loop assigns the variables depending on the tokens.
:: That will resolve the order of the tokens.
::
@ECHO off
    set v_day=
    set v_month=
    set v_year=

    SETLOCAL ENABLEEXTENSIONS
    if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
::DEBUG echo toks=%toks%
      for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
::DEBUG echo first token=%%a
        if "%%a" GEQ "A" (
          for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
            set '%%a'=%%i
            set '%%b'=%%j
            set 'yy'=%%k
          )
        )
      )
      if %'yy'% LSS 100 set 'yy'=20%'yy'%
      set Today=%'yy'%-%'mm'%-%'dd'%

    ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%

    ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]
    set datestring=%V_Year%%V_Month%%V_Day%
    echo %datestring%

    :EOF

——基珀斯

给定一个已知位置,供函数形式参考。ECHOTIMESTAMP调用显示了如何将时间戳转换为变量(本例中为DTS)。

@ECHO off

CALL :ECHOTIMESTAMP
GOTO END

:TIMESTAMP
SETLOCAL  EnableDelayedExpansion
    SET DATESTAMP=!DATE:~10,4!-!DATE:~4,2!-!DATE:~7,2!
    SET TIMESTAMP=!TIME:~0,2!-!TIME:~3,2!-!TIME:~6,2!
    SET DTS=!DATESTAMP: =0!-!TIMESTAMP: =0!
ENDLOCAL & SET "%~1=%DTS%"
GOTO :EOF

:ECHOTIMESTAMP
SETLOCAL
    CALL :TIMESTAMP DTS
    ECHO %DTS%
ENDLOCAL
GOTO :EOF

:END

EXIT /b 0

并保存到文件,timestamp.bat,下面是输出:

PowerShell 试试下面的代码。 它将在24小时内创建日期为ddmmyyhhmm的文件或文件夹变量

[int] $day = Get-Date -UFormat %d
[int] $month = Get-Date -UFormat %m
[int] $year = Get-Date -UFormat %y
[String] $date = "$($day)$($month)$($year)"
$time = Get-Date -UFormat %R
$time -replace ‘[:]’,”"
$fileFolderName = $date + time

下面是alt.msdos.batch.nt的一个变体,它独立于本地工作。

把它放在一个文本文件中,例如getDate.cmd

-----------8<------8<------------ snip -- snip ----------8<-------------
    :: Works on any NT/2k machine independent of regional date settings
    @ECHO off
    SETLOCAL ENABLEEXTENSIONS
    if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
    for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
      for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
        set '%%a'=%%i
        set '%%b'=%%j
        set '%%c'=%%k))
    if %'yy'% LSS 100 set 'yy'=20%'yy'%
    set Today=%'yy'%-%'mm'%-%'dd'% 
    ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%

    ECHO Today is Year: [%V_Year%] Month: [%V_Month%] Day: [%V_Day%]

    :EOF
-----------8<------8<------------ snip -- snip ----------8<-------------

为了让代码在没有错误msg的情况下工作到stderr,我必须在变量赋值%%a, %%b和%%c周围添加单引号。我的locale (PT)在循环/解析的某个阶段导致了错误,比如执行“set =20”之类的东西。引号为赋值语句的左侧生成一个令牌(尽管为空)。

缺点是混乱的区域变量名称:'yy', 'mm'和'dd'。但是,谁在乎呢!

这是我使用的:

::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%

如果你想进一步的想法自动备份到7-Zip档案,我有一个免费/开放的项目,你可以使用或审查的想法:http://wittman.org/ziparcy/