如何在Windows命令行上获得当前的datetime,以合适的格式在文件名中使用?

时间:2021-04-28 07:29:10

Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using date. See @npocmaka's https://*.com/a/19799236/8479

更新:现在已经是2016年了,我将使用PowerShell,除非有一个非常令人信服的向后兼容的原因,特别是由于使用日期的区域性设置问题。看看https://*.com/a/19799236/8479 @npocmaka


What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?

什么是Windows命令行语句,我可以使用它来获取当前的datetime格式,我可以将它放入一个文件名中?

I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, Code_2008-10-14_2257.zip. Is there any easy way I can do this, independent of the regional settings of the machine?

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

I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.

我不介意日期格式,最好是yyyy-mm-dd,但是任何简单的东西都可以。

So far I've got this, which on my machine gives me Tue_10_14_2008_230050_91:

到目前为止,我已经得到了这个,在我的机器上给我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

I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.

我可以接受这个,但它看起来有点笨拙。理想情况下,它会更简洁,并且有前面提到的格式。

I'm using Windows Server 2003 and Windows XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).

我使用的是Windows Server 2003和Windows XP Professional。我不想安装额外的实用程序来实现这一点(尽管我意识到有一些会做一些不错的日期格式)。

26 个解决方案

#1


573  

See Windows Batch File (.bat) to get current date in MMDDYYYY format:

请参阅Windows批处理文件(.bat)以获得当前日期的mmddyyy格式:

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%

If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:

如果你喜欢24小时/军事模式的时间,你可以用这个来代替第二次:

For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

C:> .\date.bat
2008-10-14_0642

C:>。\日期。2008 - 10 - 14 - _0642蝙蝠

If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:

如果您想要独立于区域日/月顺序的日期,您可以使用“WMIC os GET LocalDateTime”作为源,因为它是ISO命令:

@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]

C:>test.cmd
Local date is [2012-06-19 10:23:47.048]

C:>测试。cmd本地日期为[2012-06-19 10:23:47.048]

#2


91  

Regionally independent date time parsing

The output format of %DATE% and of the dir command is regionally dependent and thus neither robust nor smart. date.exe (part of UnxUtils) delivers any date and time information in any thinkable format. You may also extract the date/time information from any file with date.exe.

%日期%和dir命令的输出格式是区域性依赖的,因此既不健壮也不聪明。日期。exe (UnxUtils的一部分)以任何可思考的格式提供任何日期和时间信息。您还可以从任何文件中提取日期/时间信息。

Examples: (in a cmd-script use %% instead of %)

date.exe +"%Y-%m-%d"
2009-12-22

日期。exe + Y“% - % - % d”2009-12-22

date.exe +"%T"
18:55:03

日期。exe + 18:55:03“% T”

date.exe +"%Y%m%d %H%M%S: Any text"
20091222 185503: Any text

日期。exe +“%Y% % %H% % % %S:任何文本”20091222 185503:任何文本。

date.exe +"Text: %y/%m/%d-any text-%H.%M"
Text: 09/12/22-any text-18.55

日期。exe +”文本:% y / % m / % d-any文本——% H。% M”文本:09/12/22-any文本- 18.55

Command: date.exe +"%m-%d """%H %M %S """"
07-22 "18:55:03"`

命令:日期。exe +"%m-%d ""%H %m %S """" 07-22 "

The date/time information from a reference file:
date.exe -r c:\file.txt +"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S"

来自参考文件的日期/时间信息:日期。exe - r c:\文件。txt +"文件的时间戳。txt:Y % - % - % d % H:% m:% S”

Using it in a CMD script to get year, month, day, time information:

在CMD脚本中使用它来获得年、月、日、时间信息:

for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n

Using it in a CMD script to get a timestamp in any required format:

在CMD脚本中使用它获得任何所需格式的时间戳:

for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe +"%%y-%%m-%%d %%H:%%M:%%S"') do set timestamp=%%i

Extracting the date/time information from any reference file.

从任何引用文件中提取日期/时间信息。

for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n

Adding to a file its date/time information:

添加到文件的日期/时间信息:

for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y-%%m-%%d.%%H%%M%%S"') do ren file.txt file.%%i.txt

date.exe is part of the free GNU tools which need no installation.

日期。exe是免费GNU工具的一部分,无需安装。

NOTE: Copying date.exe into any directory which is in the search path may cause other scripts to fail that use the Windows built-in date command.

注意:复制日期。exe进入搜索路径中的任何目录,可能会导致其他脚本无法使用Windows内置的date命令。

#3


70  

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!:

另外两种不依赖于时间设置的方法(都是从:如何获得独立于本地化的数据/时间:)。而且他们都得到了一个星期的一天,他们都不需要管理员权限!

  1. MAKECAB - will work on EVERY Windows system (fast, but creates a small temp file) (the foxidrive script):

    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
    

    More information about get-date function.

    关于get-date功能的更多信息。

  2. ROBOCOPY - it's not native command for Windows XP and Windows Server 2003, but it can be downloaded from microsoft site. But is built-in in everything from Windows Vista and above:

    它不是Windows XP和Windows Server 2003的本地命令,但它可以从微软站点下载。但它内置在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
    

    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.

    还有三种使用其他Windows脚本语言的方法。他们会给你更大的灵活性,比如你可以得到一年中一周的时间,几毫秒的时间等等。

  3. JScript/batch hybrid (need to be saved as .bat). JScript is available on every system form NT and above, as a part of Windows Script Host (though can be disabled through the registry it's a rare case):

    JScript/batch混合(需要保存为.bat)。JScript在NT和上面的每个系统上都可以使用,作为Windows脚本主机的一部分(尽管可以通过注册表禁用它):

    @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());
    
  4. VSCRIPT/BATCH hybrid (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:

    VSCRIPT/批处理混合(可以在批处理文件中嵌入和执行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),", ","-")
    
  5. PowerShell - can be installed on every machine that has .NET - download from Microsoft (v1, v2, v3 (only for Windows 7 and above)). It is installed by default on everything from Windows 7/Windows Server 2008 and above:

    PowerShell——可以安装在每台有。net的机器上——从微软下载(v1, v2, v3(仅适用于Windows 7和以上))。它默认安装在Windows 7/Windows Server 2008及以上的所有产品上:

    C:\> powershell get-date -format "{dd-MMM-yyyy HH:mm}"
    

    To use it from a batch file:

    从批处理文件中使用它:

    for /f "delims=" %%# in ('powershell get-date -format "{dd-MMM-yyyy HH:mm}"') do @set _date=%%#
    
  6. Self-compiled jscript.net/batch (never seen a Windows machine without .NET, so I think this is a pretty portable):

    自编译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"));
    
  7. Logman This cannot get the year and day of the week. It's comparatively slow and also creates a temporary file and is based on the time stamps that logman puts on its log files. It will work on everything from Windows XP and above. It probably will be never used by anybody - including me - but is one more way...

    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
    
  8. One more way with WMIC which also gives week of the year and the day of the week, but not the milliseconds (for milliseconds check foxidrive's answer):

    WMIC的另一种方式是一周和一周的一周,但不是毫秒(毫秒检查foxidrive的答案):

    for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in ("%%#") do @set %%@
    echo %day%
    echo %DayOfWeek%
    echo %hour%
    echo %minute%
    echo %month%
    echo %quarter%
    echo %second%
    echo %weekinmonth%
    echo %year%
    
  9. Using TYPEPERF with some efforts to be fast and compatible with different language settings and as fast as possible:

    使用TYPEPERF和一些努力快速和兼容不同的语言设置和尽可能快:

    @echo off
    setlocal
    
    :: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance
    ::if defined USERDOMAIN_roamingprofile (set "v=v4") else (set "v=")
    
    for /f "tokens=4 delims=. " %%# in ('ver') do if %%# GTR 5 (set "v=v4") else ("v=")
    set "mon="
    for /f "skip=2 delims=," %%# in ('typeperf "\UDP%v%\*" -si 0 -sc 1') do (
       if not defined mon (
          for /f "tokens=1-7 delims=.:/ " %%a in (%%#) do (
            set mon=%%a
            set date=%%b
            set year=%%c
            set hour=%%d
            set minute=%%e
            set sec=%%f
            set ms=%%g
          )
       )
    )
    echo %year%.%mon%.%date%
    echo %hour%:%minute%:%sec%.%ms%
    endlocal
    
  10. MSHTA allows calling JavaScript methods similar to the JScript method demonstrated in #3 above. Bear in mind that JavaScript's Date object properties involving month values are numbered from 0 to 11, not 1 to 12. So a value of 9 means October.

    MSHTA允许调用类似于上面#3中演示的JScript方法的JavaScript方法。请记住,JavaScript的Date对象属性包含月值,从0到11,而不是1到12。所以9的值就是10月份。

    <!-- : Batch portion
    
    @echo off
    setlocal
    
    for /f "delims=" %%I in ('mshta "%~f0"') do set "now.%%~I"
    
    rem Display all variables beginning with "now."
    set now.
    
    goto :EOF
    
    end batch / begin HTA -->
    
    <script>
        resizeTo(0,0)
        var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),
            now = new Date(),
            props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',
                'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',
                'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',
                'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',
                'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],
            output = [];
    
        for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}
        close(fso.Write(output.join('\n')));
    </script>
    

#4


42  

Here's a variant from alt.msdos.batch.nt that works local-independently.

这里有一个来自alt.msdos.batch的变种。nt local-independently工作。

Put this in a text file, e.g. getDate.cmd

将其放入文本文件中,例如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<-------------

To get the code to work sans error msg's to stderr, I had to add the single quotes arount the variable assignments for %%a, %%b and %%c. My locale (PT) was causing errors at one stage in the looping/parsing where stuff like "set =20" was getting executed. The quotes yield a token (albeit empty) for the left-hand side of the assignment statement.

为了使代码能够工作,没有错误msg's到stderr,我必须添加单引号arount变量赋值%%a, %%b和%%c。我的语言环境(PT)在循环/解析的一个阶段导致错误,例如“set =20”被执行。在赋值语句的左侧,引号会产生一个令牌(尽管是空的)。

The downside is the messy locale variable names: 'yy', 'mm' and 'dd'. But hey, who cares!

缺点是混乱的语言环境变量名:yy, 'mm'和'dd'。但是,嘿,谁在乎!

#5


29  

I use this (again not region independent (UK))

我使用这个(不是地区独立的(英国))

set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%

#6


21  

Unfortunately this is not immune to regional settings, but it does what you want.

不幸的是,这并不是对区域设置的免疫,而是你想要的。

set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%

Amazing the stuff you can find on Wikipedia.

你可以在*上找到这些东西。

#7


16  

Please use the following script to get the current day in the command line:

请使用以下脚本在命令行中获取当前日期:

echo %Date:~0,3%day

#8


13  

Another way (credit):

另一种方法(信贷):

@For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do @( 
    Set Month=%%A
    Set Day=%%B
    Set Year=%%C
)

@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year%

Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.

请注意,我在这里的回答仍然依赖于按区域设置确定的日期和月份的顺序——不确定如何解决这个问题。

#9


13  

"d:\Program Files\7-Zip\7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip

#10


13  

This isn't really briefer but might be a more flexible way (credit):

这并不简单,但可能是一种更灵活的方式(信贷):

FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%

#11


12  

The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in Windows XP Professional and higher.

这段代码的前四行将给您提供可靠的YY DD MM yyyyyyyyyyyyyyyyyyyyyyyyy。

@echo off
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 "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

#12


8  

Here's a way to get date time in a single line:

这里有一种方法可以在单行中获得约会时间:

for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %a in ('%date% %time%') do echo %c-%a-%b %d%e

In the US this will output "yyyy-mm-dd hhmm". Different regional settings will result in different %date% outputs, but you can modify the token order.

在美国,这将输出“yyyy-mm-dd hhmm”。不同的区域设置将导致不同的%date%输出,但是您可以修改令牌顺序。

If you want a different format, modify the echo statement by rearranging the tokens or using different (or no) separators.

如果您想要一种不同的格式,可以通过重新排列令牌或使用不同的(或不)分隔符来修改echo语句。

#13


7  

And here is a similar batch-file for the time portion.

这里是时间部分的类似的批处理文件。

:: http://*.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 time settings
::
:: Gets the time in ISO 8601 24-hour format
::
:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.
:: Since ISO 8601 does not care about AM/PM, we use %time%
::
    @ECHO off
    SETLOCAL ENABLEEXTENSIONS
    for /f "tokens=1-4 delims=:,.-/ " %%i in ('echo %time%') do (
      set 'hh'=%%i
      set 'mm'=%%j
      set 'ss'=%%k
      set 'ff'=%%l)
    ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%

    ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]
    set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%
    echo %timestring%

    :EOF

--jeroen

——基珀斯

#14


7  

I changed the answer with the batch file from vMax so it works with the Dutch language too.
The Dutch - persistent as we are - have a few changes in the %date%, date/t, and date that break the original batch-file.

我用vMax的批处理文件更改了答案,所以它也使用了荷兰语。与我们一样,荷兰-持久化-在%date%,日期/t和日期上有一些变化,这打破了原始的批处理文件。

It would be nice if some people can check this against other Windows locales as well, and report back the results.
If the batch-file fails at your location, then please include the output of these two statements on the command prompt:
echo:^|date
date/t

如果有些人可以对其他的Windows环境进行检查,并报告结果,那就太好了。如果批处理文件失败在你的位置,请包括这两个语句的输出命令提示符:回声:^ |日期日期/ t

This is a sample of the output you should get from the batch-file:

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

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

Here is the revised code with comments on why:

以下是修改后的代码:

:: https://*.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

--jeroen

——基珀斯

#15


6  

Just use this line:

就用这条线:

PowerShell -Command "get-date"

#16


6  

Matthew Johnson's one-liner solution to get the one-liner date and time is eloquent and useful.

马修·约翰逊(Matthew Johnson)的一套一套的解决方案,以获得一个班轮的日期和时间是有说服力的和有用的。

It does however need a simple modification to work from within a batch file:

但是,它需要在批处理文件中进行简单的修改:

for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e

#17


6  

A function that is based on wmic:

基于wmic的函数:

:Now  -- Gets the current date and time into separate variables
::    %~1: [out] Year
::    %~2: [out] Month
::    %~3: [out] Day
::    %~4: [out] Hour
::    %~5: [out] Minute
::    %~6: [out] Second
  setlocal
  for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t
  endlocal & (
    if "%~1" neq "" set %~1=%T:~0,4%
    if "%~2" neq "" set %~2=%T:~4,2%
    if "%~3" neq "" set %~3=%T:~6,2%
    if "%~4" neq "" set %~4=%T:~8,2%
    if "%~5" neq "" set %~5=%T:~10,2%
    if "%~6" neq "" set %~6=%T:~12,2%
  )
goto:eof

Upside: Region independent. Downside: Only system administrators can run wmic.exe.

好处:地区独立。缺点:只有系统管理员才能运行wmic.exe。

Usage:

用法:

call:Now Y M D H N S
echo %Y%-%M%-%D% %H%:%N%:%S%

This echos a string like this:

这个回声是这样的:

2014-01-22 12:51:53

Note that function parameters are out-Parameters - that is, you must supply variable names instead of values.

注意,函数参数是外部参数——也就是说,您必须提供变量名称而不是值。

All parameters are optional, so call:Now Y M is a valid call if you only want to get year and month.

所有的参数都是可选的,所以调用:如果您只想得到一年和一个月,那么现在Y M是一个有效的调用。

#18


5  

This is what I've used:

这就是我所使用的:

::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:-=.%

If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/

如果您想要对7-Zip档案进行自动备份的更多想法,我有一个免费/开放的项目,您可以使用或查看想法:http://wittman.org/ziparcy/。

#19


5  

Short answer :

简短的回答:

 :: Start - Run , type:
 cmd /c "powershell get-date -format ^"{yyyy-MM-dd HH:mm:ss}^"|clip"

 :: click into target media, Ctrl + V to paste the result 

Long answer

长回答

    @echo off
    :: START USAGE  ==================================================================
    ::SET THE NICETIME 
    :: SET NICETIME=BOO
    :: CALL GetNiceTime.cmd 

    :: ECHO NICETIME IS %NICETIME%

    :: echo nice time is %NICETIME%
    :: END USAGE  ==================================================================

    echo set hhmmsss
    :: this is Regional settings dependant so tweak this according your current settings
    for /f "tokens=1-3 delims=:" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c 
    ::DEBUG ECHO hhmmsss IS %hhmmsss%
    ::DEBUG PAUSE
    echo %yyyymmdd%
        :: this is Regional settings dependant so tweak this according your current settings
    for /f "tokens=1-3 delims=." %%D in ('echo %DATE%') do set  yyyymmdd=%%F%%E%%D
    ::DEBUG ECHO yyyymmdd IS %yyyymmdd%
    ::DEBUG PAUSE


    set NICETIME=%yyyymmdd%_%hhmmsss%
    ::DEBUG echo THE NICETIME IS %NICETIME%

    ::DEBUG PAUSE

#20


4  

I had a similar problem. I have an automatic daily download from an FTP server of an encrypted file. I wanted to decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and drop the decrypted file into a folder for the correct department.

我也有类似的问题。我有一个自动每日从一个FTP服务器的一个加密文件。我希望使用gpg对文件进行解密,将文件重命名为当前日期(YYYYMMDD格式),并将解密文件放入正确的部门的文件夹中。

I went through several suggestions for renaming the file according to date and was having no luck until I stumbled upon this simple solution.

我通过了一些建议,根据日期重新命名这个文件,直到我偶然发现这个简单的解决方案时,我才幸运。

for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt

It worked perfectly (i.e., the filename comes out as "2011-06-14.txt").

(即工作的很好。,文件名是“2011-06-14 txt”。

(Source)

(源)

#21


4  

http://sourceforge.net/projects/unxutils/files/

http://sourceforge.net/projects/unxutils/files/

Look inside the ZIP file for something called "Date.exe" and rename it "DateFormat.exe" (to avoid conflicts).

查看ZIP文件中的“日期”。exe“并将其重命名为DateFormat。exe”(为了避免冲突)。

Put it in your Windows system32 folder.

把它放进你的Windows system32文件夹。

It has a lot of "date output" options.

它有很多“日期输出”选项。

For help, use DateFormat.exe --h

寻求帮助,使用DateFormat。exe - h

I'm not sure how you would put its output into an environment variable... using SET.

我不知道如何把它的输出放到一个环境变量中…使用设置。

#22


3  

Regional independent solution generating the ISO date format:

区域独立解决方案生成ISO日期格式:

rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCU\Control Panel\International" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format 
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:

What could still be optimized: Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated

还可以优化的是:如果在短时间内使用日期格式进行修改,其他流程可能会被混淆。因此,根据现有的格式字符串解析输出可能“更安全”——但会更复杂。

#23


1  

:: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format
:: - Sets environment variables %_isotime% and %_now% to current time
:: - On failure, clears these environment variables
:: Inspired on -> https://ss64.com/nt/syntax-getdate.html
:: - (cX) 2017 adolfo.dimare@gmail.com
:: - http://*.com/questions/203090
@echo off

set _isotime=
set _now=

:: Check that WMIC.exe is available
WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_

if not (%1)==() goto _help
SetLocal EnableDelayedExpansion

:: Use WMIC.exe to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    IF "%%~L"=="" goto  _WMIC_done_
        set _yyyy=%%L
        set _mm=00%%J
        set _dd=00%%G
        set _hour=00%%H
        set _minute=00%%I
        set _second=00%%K
)
:_WMIC_done_

::   1    2     3       4      5      6
:: %%G  %%H    %%I     %%J    %%K    %%L
:: Day  Hour  Minute  Month  Second  Year
:: 27   9     35      4      38      2017

:: Remove excess leading zeroes
        set _mm=%_mm:~-2%
        set _dd=%_dd:~-2%
        set _hour=%_hour:~-2%
        set _minute=%_minute:~-2%
        set _second=%_second:~-2%
:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%

:: Set date/time in ISO 8601 format:
        Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%
:: -> http://google.com/search?num=100&q=ISO+8601+format

if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am
if 1%_hour% LSS 112 goto _skip_12_
    set /a _hour=1%_hour%-12
    set _hour=%_hour:~-2%
    set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm
    :: -> https://ss64.com/nt/if.html
    :: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows
    :: 'if () else ()' will NOT set %_now% correctly !?
:_skip_12_

EndLocal & set _isotime=%_isotime% & set _now=%_now%
goto _out

:_WMIC_MISSING_
echo.
echo WMIC.exe command not available
echo - WMIC.exe needs Administrator privileges to run in Windows
echo - Usually the path to WMIC.exe is "%windir%\System32\wbem\WMIC.exe"

:_help
echo.
echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format
echo.
echo    %%_now%%     environment variable set to current date and time
echo    %%_isotime%% environment variable to current time in ISO format
echo    set _today=%%_isotime:~0,10%%
echo.

:_out
:: EOF: GetDate.cmd

#24


0  

Given a known locality, for reference in functional form. The ECHOTIMESTAMP call shows how to get the timestamp into a variable (DTS in this example.)

给定一个已知的局部性,作为函数形式的参考。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

And saved to file, timestamp.bat, here's the output:

并保存到文件,时间戳。蝙蝠,输出:

如何在Windows命令行上获得当前的datetime,以合适的格式在文件名中使用?

#25


0  

With Windows 7, this code works for me:

使用Windows 7,这段代码对我有效:

SET DATE=%date%
SET YEAR=%DATE:~0,4%
SET MONTH=%DATE:~5,2%
SET DAY=%DATE:~8,2%
ECHO %YEAR%
ECHO %MONTH%
ECHO %DAY%

SET DATE_FRM=%YEAR%-%MONTH%-%DAY% 
ECHO %DATE_FRM%

#26


-2  

I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.

我知道有很多方法已经提到。但我的方法是将它分解,以理解它是如何完成的。希望这对喜欢一步步方法的人是有帮助的。

:: Check your local date format
echo %date%

    :: Output is Mon 08/15/2016

:: get day (start index, number of characters)
::         (index starts with zero)
set myday=%DATE:~0,4%
echo %myday%
    :: output is Mon 

:: get month
set mymonth=%DATE:~4,2%
echo %mymonth%
    :: output is 08

:: get date 
set mydate=%DATE:~7,2% 
echo %mydate%
    :: output is 15

:: get year
set myyear=%DATE:~10,4%
echo %myyear%
    :: output is 2016

#1


573  

See Windows Batch File (.bat) to get current date in MMDDYYYY format:

请参阅Windows批处理文件(.bat)以获得当前日期的mmddyyy格式:

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%

If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:

如果你喜欢24小时/军事模式的时间,你可以用这个来代替第二次:

For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

C:> .\date.bat
2008-10-14_0642

C:>。\日期。2008 - 10 - 14 - _0642蝙蝠

If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:

如果您想要独立于区域日/月顺序的日期,您可以使用“WMIC os GET LocalDateTime”作为源,因为它是ISO命令:

@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]

C:>test.cmd
Local date is [2012-06-19 10:23:47.048]

C:>测试。cmd本地日期为[2012-06-19 10:23:47.048]

#2


91  

Regionally independent date time parsing

The output format of %DATE% and of the dir command is regionally dependent and thus neither robust nor smart. date.exe (part of UnxUtils) delivers any date and time information in any thinkable format. You may also extract the date/time information from any file with date.exe.

%日期%和dir命令的输出格式是区域性依赖的,因此既不健壮也不聪明。日期。exe (UnxUtils的一部分)以任何可思考的格式提供任何日期和时间信息。您还可以从任何文件中提取日期/时间信息。

Examples: (in a cmd-script use %% instead of %)

date.exe +"%Y-%m-%d"
2009-12-22

日期。exe + Y“% - % - % d”2009-12-22

date.exe +"%T"
18:55:03

日期。exe + 18:55:03“% T”

date.exe +"%Y%m%d %H%M%S: Any text"
20091222 185503: Any text

日期。exe +“%Y% % %H% % % %S:任何文本”20091222 185503:任何文本。

date.exe +"Text: %y/%m/%d-any text-%H.%M"
Text: 09/12/22-any text-18.55

日期。exe +”文本:% y / % m / % d-any文本——% H。% M”文本:09/12/22-any文本- 18.55

Command: date.exe +"%m-%d """%H %M %S """"
07-22 "18:55:03"`

命令:日期。exe +"%m-%d ""%H %m %S """" 07-22 "

The date/time information from a reference file:
date.exe -r c:\file.txt +"The timestamp of file.txt is: %Y-%m-%d %H:%M:%S"

来自参考文件的日期/时间信息:日期。exe - r c:\文件。txt +"文件的时间戳。txt:Y % - % - % d % H:% m:% S”

Using it in a CMD script to get year, month, day, time information:

在CMD脚本中使用它来获得年、月、日、时间信息:

for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n

Using it in a CMD script to get a timestamp in any required format:

在CMD脚本中使用它获得任何所需格式的时间戳:

for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe +"%%y-%%m-%%d %%H:%%M:%%S"') do set timestamp=%%i

Extracting the date/time information from any reference file.

从任何引用文件中提取日期/时间信息。

for /f "tokens=1,2,3,4,5,6* delims=," %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y,%%m,%%d,%%H,%%M,%%S"') do set yy=%%i& set mo=%%j& set dd=%%k& set hh=%%l& set mm=%%m& set ss=%%n

Adding to a file its date/time information:

添加到文件的日期/时间信息:

for /f "tokens=*" %%i in ('C:\Tools\etc\date.exe -r file.txt +"%%y-%%m-%%d.%%H%%M%%S"') do ren file.txt file.%%i.txt

date.exe is part of the free GNU tools which need no installation.

日期。exe是免费GNU工具的一部分,无需安装。

NOTE: Copying date.exe into any directory which is in the search path may cause other scripts to fail that use the Windows built-in date command.

注意:复制日期。exe进入搜索路径中的任何目录,可能会导致其他脚本无法使用Windows内置的date命令。

#3


70  

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!:

另外两种不依赖于时间设置的方法(都是从:如何获得独立于本地化的数据/时间:)。而且他们都得到了一个星期的一天,他们都不需要管理员权限!

  1. MAKECAB - will work on EVERY Windows system (fast, but creates a small temp file) (the foxidrive script):

    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
    

    More information about get-date function.

    关于get-date功能的更多信息。

  2. ROBOCOPY - it's not native command for Windows XP and Windows Server 2003, but it can be downloaded from microsoft site. But is built-in in everything from Windows Vista and above:

    它不是Windows XP和Windows Server 2003的本地命令,但它可以从微软站点下载。但它内置在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
    

    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.

    还有三种使用其他Windows脚本语言的方法。他们会给你更大的灵活性,比如你可以得到一年中一周的时间,几毫秒的时间等等。

  3. JScript/batch hybrid (need to be saved as .bat). JScript is available on every system form NT and above, as a part of Windows Script Host (though can be disabled through the registry it's a rare case):

    JScript/batch混合(需要保存为.bat)。JScript在NT和上面的每个系统上都可以使用,作为Windows脚本主机的一部分(尽管可以通过注册表禁用它):

    @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());
    
  4. VSCRIPT/BATCH hybrid (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:

    VSCRIPT/批处理混合(可以在批处理文件中嵌入和执行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),", ","-")
    
  5. PowerShell - can be installed on every machine that has .NET - download from Microsoft (v1, v2, v3 (only for Windows 7 and above)). It is installed by default on everything from Windows 7/Windows Server 2008 and above:

    PowerShell——可以安装在每台有。net的机器上——从微软下载(v1, v2, v3(仅适用于Windows 7和以上))。它默认安装在Windows 7/Windows Server 2008及以上的所有产品上:

    C:\> powershell get-date -format "{dd-MMM-yyyy HH:mm}"
    

    To use it from a batch file:

    从批处理文件中使用它:

    for /f "delims=" %%# in ('powershell get-date -format "{dd-MMM-yyyy HH:mm}"') do @set _date=%%#
    
  6. Self-compiled jscript.net/batch (never seen a Windows machine without .NET, so I think this is a pretty portable):

    自编译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"));
    
  7. Logman This cannot get the year and day of the week. It's comparatively slow and also creates a temporary file and is based on the time stamps that logman puts on its log files. It will work on everything from Windows XP and above. It probably will be never used by anybody - including me - but is one more way...

    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
    
  8. One more way with WMIC which also gives week of the year and the day of the week, but not the milliseconds (for milliseconds check foxidrive's answer):

    WMIC的另一种方式是一周和一周的一周,但不是毫秒(毫秒检查foxidrive的答案):

    for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in ("%%#") do @set %%@
    echo %day%
    echo %DayOfWeek%
    echo %hour%
    echo %minute%
    echo %month%
    echo %quarter%
    echo %second%
    echo %weekinmonth%
    echo %year%
    
  9. Using TYPEPERF with some efforts to be fast and compatible with different language settings and as fast as possible:

    使用TYPEPERF和一些努力快速和兼容不同的语言设置和尽可能快:

    @echo off
    setlocal
    
    :: Check if Windows is Windows XP and use Windows XP valid counter for UDP performance
    ::if defined USERDOMAIN_roamingprofile (set "v=v4") else (set "v=")
    
    for /f "tokens=4 delims=. " %%# in ('ver') do if %%# GTR 5 (set "v=v4") else ("v=")
    set "mon="
    for /f "skip=2 delims=," %%# in ('typeperf "\UDP%v%\*" -si 0 -sc 1') do (
       if not defined mon (
          for /f "tokens=1-7 delims=.:/ " %%a in (%%#) do (
            set mon=%%a
            set date=%%b
            set year=%%c
            set hour=%%d
            set minute=%%e
            set sec=%%f
            set ms=%%g
          )
       )
    )
    echo %year%.%mon%.%date%
    echo %hour%:%minute%:%sec%.%ms%
    endlocal
    
  10. MSHTA allows calling JavaScript methods similar to the JScript method demonstrated in #3 above. Bear in mind that JavaScript's Date object properties involving month values are numbered from 0 to 11, not 1 to 12. So a value of 9 means October.

    MSHTA允许调用类似于上面#3中演示的JScript方法的JavaScript方法。请记住,JavaScript的Date对象属性包含月值,从0到11,而不是1到12。所以9的值就是10月份。

    <!-- : Batch portion
    
    @echo off
    setlocal
    
    for /f "delims=" %%I in ('mshta "%~f0"') do set "now.%%~I"
    
    rem Display all variables beginning with "now."
    set now.
    
    goto :EOF
    
    end batch / begin HTA -->
    
    <script>
        resizeTo(0,0)
        var fso = new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1),
            now = new Date(),
            props=['getDate','getDay','getFullYear','getHours','getMilliseconds','getMinutes',
                'getMonth','getSeconds','getTime','getTimezoneOffset','getUTCDate','getUTCDay',
                'getUTCFullYear','getUTCHours','getUTCMilliseconds','getUTCMinutes','getUTCMonth',
                'getUTCSeconds','getYear','toDateString','toGMTString','toLocaleDateString',
                'toLocaleTimeString','toString','toTimeString','toUTCString','valueOf'],
            output = [];
    
        for (var i in props) {output.push(props[i] + '()=' + now[props[i]]())}
        close(fso.Write(output.join('\n')));
    </script>
    

#4


42  

Here's a variant from alt.msdos.batch.nt that works local-independently.

这里有一个来自alt.msdos.batch的变种。nt local-independently工作。

Put this in a text file, e.g. getDate.cmd

将其放入文本文件中,例如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<-------------

To get the code to work sans error msg's to stderr, I had to add the single quotes arount the variable assignments for %%a, %%b and %%c. My locale (PT) was causing errors at one stage in the looping/parsing where stuff like "set =20" was getting executed. The quotes yield a token (albeit empty) for the left-hand side of the assignment statement.

为了使代码能够工作,没有错误msg's到stderr,我必须添加单引号arount变量赋值%%a, %%b和%%c。我的语言环境(PT)在循环/解析的一个阶段导致错误,例如“set =20”被执行。在赋值语句的左侧,引号会产生一个令牌(尽管是空的)。

The downside is the messy locale variable names: 'yy', 'mm' and 'dd'. But hey, who cares!

缺点是混乱的语言环境变量名:yy, 'mm'和'dd'。但是,嘿,谁在乎!

#5


29  

I use this (again not region independent (UK))

我使用这个(不是地区独立的(英国))

set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%

#6


21  

Unfortunately this is not immune to regional settings, but it does what you want.

不幸的是,这并不是对区域设置的免疫,而是你想要的。

set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%

Amazing the stuff you can find on Wikipedia.

你可以在*上找到这些东西。

#7


16  

Please use the following script to get the current day in the command line:

请使用以下脚本在命令行中获取当前日期:

echo %Date:~0,3%day

#8


13  

Another way (credit):

另一种方法(信贷):

@For /F "tokens=2,3,4 delims=/ " %%A in ('Date /t') do @( 
    Set Month=%%A
    Set Day=%%B
    Set Year=%%C
)

@echo DAY = %Day%
@echo Month = %Month%
@echo Year = %Year%

Note that both my answers here are still reliant on the order of the day and month as determined by regional settings - not sure how to work around that.

请注意,我在这里的回答仍然依赖于按区域设置确定的日期和月份的顺序——不确定如何解决这个问题。

#9


13  

"d:\Program Files\7-Zip\7z.exe" a -r code_%date:~10,4%-%date:~4,2%-%date:~7,2%.zip

#10


13  

This isn't really briefer but might be a more flexible way (credit):

这并不简单,但可能是一种更灵活的方式(信贷):

FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%

#11


12  

The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in Windows XP Professional and higher.

这段代码的前四行将给您提供可靠的YY DD MM yyyyyyyyyyyyyyyyyyyyyyyyy。

@echo off
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 "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%" & set "fullstamp=%YYYY%-%MM%-%DD%_%HH%%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

#12


8  

Here's a way to get date time in a single line:

这里有一种方法可以在单行中获得约会时间:

for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %a in ('%date% %time%') do echo %c-%a-%b %d%e

In the US this will output "yyyy-mm-dd hhmm". Different regional settings will result in different %date% outputs, but you can modify the token order.

在美国,这将输出“yyyy-mm-dd hhmm”。不同的区域设置将导致不同的%date%输出,但是您可以修改令牌顺序。

If you want a different format, modify the echo statement by rearranging the tokens or using different (or no) separators.

如果您想要一种不同的格式,可以通过重新排列令牌或使用不同的(或不)分隔符来修改echo语句。

#13


7  

And here is a similar batch-file for the time portion.

这里是时间部分的类似的批处理文件。

:: http://*.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 time settings
::
:: Gets the time in ISO 8601 24-hour format
::
:: Note that %time% gets you fractions of seconds, and time /t doesn't, but gets you AM/PM if your locale supports that.
:: Since ISO 8601 does not care about AM/PM, we use %time%
::
    @ECHO off
    SETLOCAL ENABLEEXTENSIONS
    for /f "tokens=1-4 delims=:,.-/ " %%i in ('echo %time%') do (
      set 'hh'=%%i
      set 'mm'=%%j
      set 'ss'=%%k
      set 'ff'=%%l)
    ENDLOCAL & SET v_Hour=%'hh'%& SET v_Minute=%'mm'%& SET v_Second=%'ss'%& SET v_Fraction=%'ff'%

    ECHO Now is Hour: [%V_Hour%] Minute: [%V_Minute%] Second: [%v_Second%] Fraction: [%v_Fraction%]
    set timestring=%V_Hour%%V_Minute%%v_Second%.%v_Fraction%
    echo %timestring%

    :EOF

--jeroen

——基珀斯

#14


7  

I changed the answer with the batch file from vMax so it works with the Dutch language too.
The Dutch - persistent as we are - have a few changes in the %date%, date/t, and date that break the original batch-file.

我用vMax的批处理文件更改了答案,所以它也使用了荷兰语。与我们一样,荷兰-持久化-在%date%,日期/t和日期上有一些变化,这打破了原始的批处理文件。

It would be nice if some people can check this against other Windows locales as well, and report back the results.
If the batch-file fails at your location, then please include the output of these two statements on the command prompt:
echo:^|date
date/t

如果有些人可以对其他的Windows环境进行检查,并报告结果,那就太好了。如果批处理文件失败在你的位置,请包括这两个语句的输出命令提示符:回声:^ |日期日期/ t

This is a sample of the output you should get from the batch-file:

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

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

Here is the revised code with comments on why:

以下是修改后的代码:

:: https://*.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

--jeroen

——基珀斯

#15


6  

Just use this line:

就用这条线:

PowerShell -Command "get-date"

#16


6  

Matthew Johnson's one-liner solution to get the one-liner date and time is eloquent and useful.

马修·约翰逊(Matthew Johnson)的一套一套的解决方案,以获得一个班轮的日期和时间是有说服力的和有用的。

It does however need a simple modification to work from within a batch file:

但是,它需要在批处理文件中进行简单的修改:

for /f "tokens=2,3,4,5,6 usebackq delims=:/ " %%a in ('%date% %time%') do echo %%c-%%a-%%b %%d%%e

#17


6  

A function that is based on wmic:

基于wmic的函数:

:Now  -- Gets the current date and time into separate variables
::    %~1: [out] Year
::    %~2: [out] Month
::    %~3: [out] Day
::    %~4: [out] Hour
::    %~5: [out] Minute
::    %~6: [out] Second
  setlocal
  for /f %%t in ('wmic os get LocalDateTime ^| findstr /b [0-9]') do set T=%%t
  endlocal & (
    if "%~1" neq "" set %~1=%T:~0,4%
    if "%~2" neq "" set %~2=%T:~4,2%
    if "%~3" neq "" set %~3=%T:~6,2%
    if "%~4" neq "" set %~4=%T:~8,2%
    if "%~5" neq "" set %~5=%T:~10,2%
    if "%~6" neq "" set %~6=%T:~12,2%
  )
goto:eof

Upside: Region independent. Downside: Only system administrators can run wmic.exe.

好处:地区独立。缺点:只有系统管理员才能运行wmic.exe。

Usage:

用法:

call:Now Y M D H N S
echo %Y%-%M%-%D% %H%:%N%:%S%

This echos a string like this:

这个回声是这样的:

2014-01-22 12:51:53

Note that function parameters are out-Parameters - that is, you must supply variable names instead of values.

注意,函数参数是外部参数——也就是说,您必须提供变量名称而不是值。

All parameters are optional, so call:Now Y M is a valid call if you only want to get year and month.

所有的参数都是可选的,所以调用:如果您只想得到一年和一个月,那么现在Y M是一个有效的调用。

#18


5  

This is what I've used:

这就是我所使用的:

::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:-=.%

If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/

如果您想要对7-Zip档案进行自动备份的更多想法,我有一个免费/开放的项目,您可以使用或查看想法:http://wittman.org/ziparcy/。

#19


5  

Short answer :

简短的回答:

 :: Start - Run , type:
 cmd /c "powershell get-date -format ^"{yyyy-MM-dd HH:mm:ss}^"|clip"

 :: click into target media, Ctrl + V to paste the result 

Long answer

长回答

    @echo off
    :: START USAGE  ==================================================================
    ::SET THE NICETIME 
    :: SET NICETIME=BOO
    :: CALL GetNiceTime.cmd 

    :: ECHO NICETIME IS %NICETIME%

    :: echo nice time is %NICETIME%
    :: END USAGE  ==================================================================

    echo set hhmmsss
    :: this is Regional settings dependant so tweak this according your current settings
    for /f "tokens=1-3 delims=:" %%a in ('echo %time%') do set hhmmsss=%%a%%b%%c 
    ::DEBUG ECHO hhmmsss IS %hhmmsss%
    ::DEBUG PAUSE
    echo %yyyymmdd%
        :: this is Regional settings dependant so tweak this according your current settings
    for /f "tokens=1-3 delims=." %%D in ('echo %DATE%') do set  yyyymmdd=%%F%%E%%D
    ::DEBUG ECHO yyyymmdd IS %yyyymmdd%
    ::DEBUG PAUSE


    set NICETIME=%yyyymmdd%_%hhmmsss%
    ::DEBUG echo THE NICETIME IS %NICETIME%

    ::DEBUG PAUSE

#20


4  

I had a similar problem. I have an automatic daily download from an FTP server of an encrypted file. I wanted to decrypt the file using gpg, rename the file to the current date (YYYYMMDD format) and drop the decrypted file into a folder for the correct department.

我也有类似的问题。我有一个自动每日从一个FTP服务器的一个加密文件。我希望使用gpg对文件进行解密,将文件重命名为当前日期(YYYYMMDD格式),并将解密文件放入正确的部门的文件夹中。

I went through several suggestions for renaming the file according to date and was having no luck until I stumbled upon this simple solution.

我通过了一些建议,根据日期重新命名这个文件,直到我偶然发现这个简单的解决方案时,我才幸运。

for /f "tokens=1-5 delims=/ " %%d in ("%date%") do rename "decrypted.txt" %%g-%%e-%%f.txt

It worked perfectly (i.e., the filename comes out as "2011-06-14.txt").

(即工作的很好。,文件名是“2011-06-14 txt”。

(Source)

(源)

#21


4  

http://sourceforge.net/projects/unxutils/files/

http://sourceforge.net/projects/unxutils/files/

Look inside the ZIP file for something called "Date.exe" and rename it "DateFormat.exe" (to avoid conflicts).

查看ZIP文件中的“日期”。exe“并将其重命名为DateFormat。exe”(为了避免冲突)。

Put it in your Windows system32 folder.

把它放进你的Windows system32文件夹。

It has a lot of "date output" options.

它有很多“日期输出”选项。

For help, use DateFormat.exe --h

寻求帮助,使用DateFormat。exe - h

I'm not sure how you would put its output into an environment variable... using SET.

我不知道如何把它的输出放到一个环境变量中…使用设置。

#22


3  

Regional independent solution generating the ISO date format:

区域独立解决方案生成ISO日期格式:

rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCU\Control Panel\International" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format 
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:

What could still be optimized: Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated

还可以优化的是:如果在短时间内使用日期格式进行修改,其他流程可能会被混淆。因此,根据现有的格式字符串解析输出可能“更安全”——但会更复杂。

#23


1  

:: GetDate.cmd -> Uses WMIC.exe to get current date and time in ISO 8601 format
:: - Sets environment variables %_isotime% and %_now% to current time
:: - On failure, clears these environment variables
:: Inspired on -> https://ss64.com/nt/syntax-getdate.html
:: - (cX) 2017 adolfo.dimare@gmail.com
:: - http://*.com/questions/203090
@echo off

set _isotime=
set _now=

:: Check that WMIC.exe is available
WMIC.exe Alias /? >NUL 2>&1 || goto _WMIC_MISSING_

if not (%1)==() goto _help
SetLocal EnableDelayedExpansion

:: Use WMIC.exe to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC.exe Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    IF "%%~L"=="" goto  _WMIC_done_
        set _yyyy=%%L
        set _mm=00%%J
        set _dd=00%%G
        set _hour=00%%H
        set _minute=00%%I
        set _second=00%%K
)
:_WMIC_done_

::   1    2     3       4      5      6
:: %%G  %%H    %%I     %%J    %%K    %%L
:: Day  Hour  Minute  Month  Second  Year
:: 27   9     35      4      38      2017

:: Remove excess leading zeroes
        set _mm=%_mm:~-2%
        set _dd=%_dd:~-2%
        set _hour=%_hour:~-2%
        set _minute=%_minute:~-2%
        set _second=%_second:~-2%
:: Syntax -> %variable:~num_chars_to_skip,num_chars_to_keep%

:: Set date/time in ISO 8601 format:
        Set _isotime=%_yyyy%-%_mm%-%_dd%T%_hour%:%_minute%:%_second%
:: -> http://google.com/search?num=100&q=ISO+8601+format

if 1%_hour% LSS 112 set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%am
if 1%_hour% LSS 112 goto _skip_12_
    set /a _hour=1%_hour%-12
    set _hour=%_hour:~-2%
    set _now=%_isotime:~0,10% %_hour%:%_minute%:%_second%pm
    :: -> https://ss64.com/nt/if.html
    :: -> http://google.com/search?num=100&q=SetLocal+EndLocal+Windows
    :: 'if () else ()' will NOT set %_now% correctly !?
:_skip_12_

EndLocal & set _isotime=%_isotime% & set _now=%_now%
goto _out

:_WMIC_MISSING_
echo.
echo WMIC.exe command not available
echo - WMIC.exe needs Administrator privileges to run in Windows
echo - Usually the path to WMIC.exe is "%windir%\System32\wbem\WMIC.exe"

:_help
echo.
echo GetDate.cmd: Uses WMIC.exe to get current date and time in ISO 8601 format
echo.
echo    %%_now%%     environment variable set to current date and time
echo    %%_isotime%% environment variable to current time in ISO format
echo    set _today=%%_isotime:~0,10%%
echo.

:_out
:: EOF: GetDate.cmd

#24


0  

Given a known locality, for reference in functional form. The ECHOTIMESTAMP call shows how to get the timestamp into a variable (DTS in this example.)

给定一个已知的局部性,作为函数形式的参考。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

And saved to file, timestamp.bat, here's the output:

并保存到文件,时间戳。蝙蝠,输出:

如何在Windows命令行上获得当前的datetime,以合适的格式在文件名中使用?

#25


0  

With Windows 7, this code works for me:

使用Windows 7,这段代码对我有效:

SET DATE=%date%
SET YEAR=%DATE:~0,4%
SET MONTH=%DATE:~5,2%
SET DAY=%DATE:~8,2%
ECHO %YEAR%
ECHO %MONTH%
ECHO %DAY%

SET DATE_FRM=%YEAR%-%MONTH%-%DAY% 
ECHO %DATE_FRM%

#26


-2  

I know that there are numerous ways mentioned already. But here is my way to break it down to understand how it is done. Hopefully, it is helpful for someone who like step by step method.

我知道有很多方法已经提到。但我的方法是将它分解,以理解它是如何完成的。希望这对喜欢一步步方法的人是有帮助的。

:: Check your local date format
echo %date%

    :: Output is Mon 08/15/2016

:: get day (start index, number of characters)
::         (index starts with zero)
set myday=%DATE:~0,4%
echo %myday%
    :: output is Mon 

:: get month
set mymonth=%DATE:~4,2%
echo %mymonth%
    :: output is 08

:: get date 
set mydate=%DATE:~7,2% 
echo %mydate%
    :: output is 15

:: get year
set myyear=%DATE:~10,4%
echo %myyear%
    :: output is 2016