How do I get the day month and year from a Windows cmd.exe script?

前端 未结 14 1355
长情又很酷
长情又很酷 2020-12-23 17:02

How do I get the current day month and year from inside a Windows cmd script? I need to get each value into a separate variable.

相关标签:
14条回答
  • 2020-12-23 17:13

    LANGUAGE INDEPENDENCY:

    The Andrei Coscodan solution is language dependent, so a way to try to fix it is to reserve all the tags for each field: year, month and day on target languages. Consider Portugese and English, after the parsing do a final set as:

    set Year=%yy%%aa%
    set Month=%mm%
    set Day=%dd%
    

    Look for the year setting, I used both tags from English and Portuguese, it worked for me in Brazil where we have these two languages as the most common in Windows instalations. I expect this will work also for some languages with Latin origin like as French, Spanish, and so on.

    Well, the full script could be:

    @echo off
    setlocal enabledelayedexpansion
    
    :: Extract date fields - language dependent
    for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (
            set v1=%%i& set v2=%%j& set v3=%%k
            if "%%i:~0,1%%" gtr "9" (set v1=%%j& set v2=%%k& set v3=%%l)
    
            for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo.^|date') do (
                set %%m=!v1!& set %%n=!v2!& set %%o=!v3!
        )
    )
    
    :: Final set for language independency (English and Portuguese - maybe works for Spanish and French)
    set year=%yy%%aa%
    set month=%mm%
    set day=%dd%
    
    
    :: Testing
    echo Year:[%year%] - month:[%month%] - day:[%day%]
    
    endlocal
    pause
    

    I hope this helps someone that deal with diferent languages.

    0 讨论(0)
  • 2020-12-23 17:13

    Based on the great answers above, I would like to add this variation as a one-liner that simply assigns the year to the %year% environment variable:

    for /f "skip=1 tokens=2 delims==" %%y in ('wmic PATH Win32_LocalTime GET Year /value') do set year=%%y
    
    0 讨论(0)
  • 2020-12-23 17:16

    I think that Andrei Coscodan answer is the best when you can't make many assumptions. But sometimes having a one-liner is nice if you can make some some assumptions. This solution assumes that 'date \t' will return one of two formats. On WindowsXP 'date /t 'returns "11/23/2011", but on Windows7 it returns "Wed 11/23/2011".

    FOR /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set mm=%%a&set dd=%%b&set yyyy=%%c& (if "%%a:~0,1" gtr "9" set mm=%%b&setdd=%%c&set yyyy=%%d))
    :: Test results
    echo day in 'DD' format is '%dd%'; month in 'MM' format is '%mm%'; year in 'YYYY' format is '%yyyy%'
    

    Thanks to Andrei Consodan answer to help me with this one-line solution.

    0 讨论(0)
  • 2020-12-23 17:17

    Extract Day, Month and Year

    The highest voted function and the accepted one do NOT work locale-independently since the DATE command is subject to localization too. For example (the accepted one): In English you have YYYY for year and in Holland it is JJJJ. So this is a no-go. The following script takes the users' localization from the registry, which is locale-independent.

    @echo off
    
    ::: Begin set date
    setlocal EnableExtensions EnableDelayedExpansion
    
    :: Determine short date format (independent from localization) from registry
    for /f "skip=1 tokens=3-5 delims=- " %%L in ( '2^>nul reg query "HKCU\Control Panel\International" /v "sShortDate"' ) do ( 
    
        :: Since we can have multiple (short) date formats we only use the first char from the format in a new variable
        set "_L=%%L" && set "_L=!_L:~0,1!" && set "_M=%%M" && set "_M=!_M:~0,1!" && set "_N=%%N" && set "_N=!_N:~0,1!"
    
        :: Now assign the date values to the new vars
        for /f "tokens=2-4 delims=/-. " %%D in ( "%date%" ) do ( set "!_L!=%%D" && set "!_M!=%%E" && set "!_N!=%%F" )
    )
    
    
    :: Print the values as is
    echo.
    echo This is the original date string --^> %date%
    echo These are the splitted values    --^> Day: %d%, Month:%m%, Year: %y%.
    echo.
    
    endlocal
    

    Extract only the Year

    For a script I wrote I wanted only to extract the year (locale-independent) so I came up with this oneliner as I couldn't find any solution. It uses the 'DATE' var, multiple delimiters and checks for a number greater than 31. That then will be the current year. It's low on resources in contrast to some of the other solutions.

    @echo off
    
    setlocal EnableExtensions
    
    for /f " tokens=2-4 delims=-./ " %%D in ( "%date%" ) do ( if %%D gtr 31 ( set "_YEAR=%%D" ) else ( if %%E gtr 31 ( set "_YEAR=%%E" ) else ( if %%F gtr 31 ( set "_YEAR=%%F" ) ) ) )
    
    echo And the year is... %_YEAR%.
    echo.
    
    endlocal
    
    0 讨论(0)
  • 2020-12-23 17:18

    The only reliably way I know is to use VBScript to do the heavy work for you. There is no portable way of getting the current date in a usable format with a batch file alone. The following VBScript file

    Wscript.Echo("set Year=" & DatePart("yyyy", Date))
    Wscript.Echo("set Month=" & DatePart("m", Date))
    Wscript.Echo("set Day=" & DatePart("d", Date))
    

    and this batch snippet

    for /f "delims=" %%x in ('cscript /nologo date.vbs') do %%x
    echo %Year%-%Month%-%Day%
    

    should work, though.

    While you can get the current date in a batch file with either date /t or the %date% pseudo-variable, both follow the current locale in what they display. Which means you get the date in potentially any format and you have no way of parsing that.

    0 讨论(0)
  • 2020-12-23 17:22

    I have converted to using Powershell calls for this purpose in my scripts. It requires script execution permission and is by far the slowest option. However it is also localization independent, very easy to write and read, and it is much more feasible to perform adjustments to the date like addition/subtraction or get the last day of the month, etc.

    Here is how to get the day, month, and year

    for /f %%i in ('"powershell (Get-Date).ToString(\"dd\")"') do set day=%%i
    for /f %%i in ('"powershell (Get-Date).ToString(\"MM\")"') do set month=%%i
    for /f %%i in ('"powershell (Get-Date).ToString(\"yyyy\")"') do set year=%%i
    

    Or, here is yesterday's date in yyyy-MM-dd format

    for /f %%i in ('"powershell (Get-Date).AddDays(-1).ToString(\"yyyy-MM-dd\")"') do set yesterday=%%i

    Day of the week

    for /f %%d in ('"powershell (Get-Date).DayOfWeek"') do set DayOfWeek=%%d

    Current time plus 15 minutes

    for /f %%i in ('"powershell (Get-Date).AddMinutes(15).ToString(\"HH:mm\")"') do set time=%%i

    0 讨论(0)
提交回复
热议问题