How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

前端 未结 28 2203
别跟我提以往
别跟我提以往 2020-11-21 05:28

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 setting

28条回答
  •  一个人的身影
    2020-11-21 06:02

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

    Put this in a text file, e.g. 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.

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

提交回复
热议问题