Batch Script: Validate Date Input

后端 未结 6 1322
予麋鹿
予麋鹿 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:13

    The Batch file below check that the inserted date have the right format and that it represent a valid date, that is, that have the right number of days in each month, even for February on leap years!

    @echo off
    setlocal EnableDelayedExpansion
    
    set i=0
    for %%a in (31 28 31 30 31 30 31 31 30 31 30 31) do (
       set /A i+=1
       set dpm[!i!]=%%a
    )
    
    set /P "inDate=Please insert date (MM-DD-YYYY format): "
    if "%inDate:~2,1%%inDate:~5,1%" neq "--" goto invalidDate
    for /F "tokens=1-3 delims=-" %%a in ("%inDate%") do set "MM=%%a" & set "DD=%%b" & set "YYYY=%%c"
    ver > NUL
    set /A month=1%MM%-100, day=1%DD%-100, year=1%YYYY%-10000, leap=year%%4  2>NUL
    if errorlevel 1 goto invalidDate
    if not defined dpm[%month%] goto invalidDate
    if %leap% equ 0 set dpm[2]=29
    if %day% gtr !dpm[%month%]! goto invalidDate
    if %day% lss 1 goto invalidDate
    echo Date correct: %YYYY%-%MM%-%DD%
    goto :EOF
    
    :invalidDate
    echo Bad date
    

提交回复
热议问题