0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windowsバッチ(.bat)学習メモ 日付(yyyymmdd)に対するチェック

Posted at
  • ※yyyymmdd、という8桁の半角数字以外の値が渡された場合は、
    一切の例外を認めずに弾くようになってしまっています。
    ×:半角数字以外が含まれる文字列
    ×:半角数字のみで構成されているが、8桁ではない文字列
1_Controller.bat
@echo off

set modelBat="%cd%\2_Model.bat"
set wantChkTarget=任意の日付(yyyymmdd形式)
call %modelBat% %wantChkTarget%
2_Model.bat
@echo off
setlocal enabledelayedexpansion

::1.引数チェック(個数が適切かどうか)
if "%1"=="" set errMsg=引数がありません。
if not "%2"=="" set errMsg=引数が過剰です。
if not "!errMsg!"=="" goto incorrectArgs
:: ↑ if not defined errMsgでいけるかと思ったけど、駄目そう...?
set yyyymmdd=%1

::2.引数チェック(値が数値であるかどうか)
set /a dummy=%yyyymmdd% 2>nul
:: ↑ 「>nul」だとエラーメッセージは出力されてしまうので、「2」を追加してそれも抑制する
if %errorlevel% neq 0 (
    set errMsg=第一引数は、8桁の半角数字によるyyyymmdd形式の文字列で、基準日を指定してください。 入力:%yyyymmdd%
    goto incorrectArgs
)

::3.引数チェック(存在する年月が指定されているかどうか)
::3-1.桁数をチェック(yyyymmdd形式で入力されていれば、8桁になる)
set dummy=%yyyymmdd%
set count=0
:chkDigit
set dummy=!dummy:~1!
set /a count+=1
if not "!dummy!"=="" (
    goto chkDigit
) else (
    if not !count! equ 8 (
        set errMsg=第一引数は、8桁の半角数字によるyyyymmdd形式の文字列で、基準日を指定してください。 入力:%yyyymmdd%
        goto incorrectArgs
    )
)
::3-2.月部分をチェック
set yyyy=%yyyymmdd:~0,4%
set mm=%yyyymmdd:~4,2%
set dd=%yyyymmdd:~6,2%
if %mm% lss 1 if %mm% gtr 12 (
    set errMsg=第一引数で、存在しない月が指定されています 入力:%yyyymmdd%
    goto incorrectArgs
)
::3-3.日部分をチェック
::3-3-1.月ごとの最終日を取得
set maxDatePerMonth=31 28 31 30 31 30 31 31 30 31 30 31
if %mm% equ 2 (
    set reminderOfFour=%yyyy% %% 4
    set reminderOfOneHun=%yyyy% %% 100
    set reminderOfFourHun=%yyyy% %% 400
    if %reminderOfFour% equ 0 if %reminderOfOneHun% equ 0 if %reminderOfFourHun% neq 0 goto notUruuYear
    set maxDatePerMonth=31 29 31 30 31 30 31 31 30 31 30 31
)
:notUruuYear
::3-3-2.月初から月末の間に日が入っているか確認
set /a dummy=%mm%+0
set dummyToken=!dummy!
for /f "tokens=%dummyToken%" %%m in ("!maxDatePerMonth!") do set dummy=%%m
if %dd% lss 1 if %dd% gtr !dummy! (
    set errMsg=第一引数に、存在しない日付が指定されています。 入力:%yyyymmdd%
    goto incorrectArgs
)

::4-A.正常終了
.echo
echo チェック完了、問題なし
echo 引数:%yyyymmdd%
.echo
exit /b

::4-B.異常終了
:incorrectArgs
echo.
echo --------------------------------------------------
echo 処理中止
echo 原因:!errMsg!
echo --------------------------------------------------
echo.
echo 何かキーを押すとウィンドウが閉じます...
pause>nul
exit
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?