【发布时间】:2020-07-17 17:38:42
【问题描述】:
我有以下代码从用户 MM-DD-YYYY 获取日期并验证它是该格式,然后将其转换为 YYYY-MM-DD。一切正常……主要是。但是,我无法弄清楚为什么当它到达 YYYY 部分时它会停止验证。它可能缺少一些代码来检查。
:sof
GOTO :ValidDate
:: Get and validate date
:ValidDate
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=First Contact 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.
ECHO.
GOTO :loopCompanyType
:invalidDate
ECHO Date input is invalid. Fomat must be MM-DD-YYYY.
ECHO.
PAUSE
GOTO :sof
这是我最初拥有的月+日+年的代码,并结合但也无法验证。
:ValidateDate
ECHO.
SET /P month="Please enter First Contact Month (format must be MM)
ECHO.
IF [%month:~2%] NEQ [] echo Month format entered incorrectly. Try again. & GOTO :ValidateDate
SET /P day="Please enter First Contact Day (format must be DD)
ECHO.
IF [%day:~2%] NEQ [] echo Day format entered incorrectly. Try again. & GOTO :ValidateDate
SET /P year="Please enter First Contact Year (format must be YYYY)
ECHO.
IF [%month:~4%] NEQ [] echo Year format entered incorrectly. Try again. & GOTO :ValidateDate
SET FCD=%year%-%month%-%day%
CHOICE /C YN /M "Is the First Contact Date %FCD% correct?"
IF ERRORLEVEL ==2 GOTO :ValidateDate
IF ERRORLEVEL ==1 GOTO :loopCompanyType
【问题讨论】:
-
欢迎来到 Stack Overflow。请花2分钟tour。此外,打开Help center 并至少阅读How to Ask。然后,edit 您的问题提供minimal reproducible example。例如,我不明白 当它到达 YYYY 部分时它停止验证 断言。会发生什么?
-
请注意
--检查只会确认用户在这两个位置输入了这两个字符。它不会验证输入的字符数是否正确,或者非-字符是否都是整数。 -
我最初的想法是,如果对您的最终用户没有太大的不便,请询问年份、月份、日期,并在使用时检查每个您对它们都有效感到满意,请根据需要自行加入。
-
@JosefZ 您可以输入 MM-DD-Y 并且它认为它是有效的。它需要验证 YYYY 是正确的格式。
-
@Compo 我确实尝试过类似这样的首字母。我最初在 2013 年得到了这个脚本。我在批处理方面不是最棒的,最近才意识到它已经坏了。我使用了上面发布的原始代码,因为它对用户的提示较少。我也永远无法得到月+日+年,然后结合起来验证正确。编辑显示我的原始代码。
标签: batch-file