Batch Script: Validate Date Input

后端 未结 6 1320
予麋鹿
予麋鹿 2020-12-21 06:39

I have a batch file that I use to create new project folders for clients that walks a user through the creation process and adds the appropriate files and folders to a centr

6条回答
  •  我在风中等你
    2020-12-21 07:26

    @ECHO OFF
    SETLOCAL enabledelayedexpansion
    CALL :getverdate
    ECHO DATE %indate% is OK.
    GOTO :EOF
    ::
    :: Get and verify date in format mm-dd-yyyy; reformat as yyyy-mmm-dd
    ::
    :regetdate
    ECHO "%indate%" is not in format "MM-DD-YYYY" or is invalid
    :getverdate
    SET /p indate="Please insert date (MM-DD-YYYY format): "
    IF NOT "%indate:~2,1%%indate:~5,1%"=="--" GOTO regetdate
    SET checkdate=9%indate:-=%
    IF NOT "%checkdate:~8%"=="%checkdate:~8,1%" GOTO regetdate
    FOR %%a IN (0 1 2 3 4 5 6 7 8 9) DO SET checkdate=!checkdate:%%a=!
    IF DEFINED checkdate GOTO regetdate
    IF %indate:~3,2%==00 GOTO regetdate
    FOR %%i IN (01:31 02:29 03:31 04:30 05:31 06:30 07:31 08:31 09:30 10:31 11:30 12:31) DO (
     FOR /f "tokens=1,2delims=:" %%j IN ("%%i") DO IF %%j==%indate:~0,2% if "%%k" geq "%indate:~3,2%" GOTO goodday 
    )
    GOTO regetdate
    :goodday
    IF "%indate:~-4%" geq "1980" IF "%indate:~-4%" leq "2099" GOTO goodyear
    GOTO regetdate
    :goodyear
    SET /a checkdate=%indate:~-4% %% 4
    IF "%indate:~0,2%%indate:~3,2%"=="0229" IF %checkdate% neq 0 GOTO regetdate
    SET indate=%indate:~-4%-%indate:~0,2%-%indate:~3,2%
    GOTO :eof
    

    Here's another 'get and validate date` routine.

    Note that in your code you should never set a variable called date. %date% will return the current date - it's a "magic variable" controlled by CMD. Other such variables include %time%, %random% and %errorlevel%. Setting any of these overrides the system-established value.

提交回复
热议问题