LoginSignup
1

More than 5 years have passed since last update.

バッチファイルで書いた cal コマンドです。

だいぶむかしに書いたものですが、ちょっとだけ修正しました。

cal.bat
@echo off

set SELF=%~n0
set HELP=Usage: %SELF% MONTH YEAR

setlocal enabledelayedexpansion
  :: 値が数値か確認
  (echo %~1) | findstr /r "[^0-9]." > NUL && (
    >&2 echo %HELP%
    exit /b 1
  )
  (echo %~2) | findstr /r "[^0-9]." > NUL && (
    >&2 echo %HELP%
    exit /b 1
  )

  :: 位置パラメーターを取得
  set y=%~2
  set m=%~1

  :: 値が範囲内か確認
  if %m% lss  1 (
    >&2 echo %SELF%: illegal month value: use 1-12
    exit /b 1
  )
  if %m% gtr 12 (
    >&2 echo %SELF%: illegal month value: use 1-12
    exit /b 1
  )
  if %y% lss    1 (
    >&2 echo %SELF%: illegal year value: use 1-9999
    exit /b 1
  )
  if %y% gtr 9999 (
    >&2 echo %SELF%: illegal year value: use 1-9999
    exit /b 1
  )

  :: 指定された日の曜日を取得(月初の曜日)
  call :get_day_of_week %y% %m% 1
  set w=%ERRORLEVEL%

  :: 指定された月の日数を取得
  set i=1
  for %%i in (31 28 31 30 31 30 31 31 30 31 30 31) do (
    set d[!i!]=%%i
    set /a i+=1
  )
  set d=!d[%m%]!

  :: うるう年を考慮
  if %m% equ 2 (call :is_leap_year %y% || set /a d+=1)

  :: カレンダーを表示
  if %m% lss 10 (
    echo %y%/ %m%
  ) else (
    echo %y%/%m%
  )
  echo Su Mo Tu We Th Fr Sa
  set t=
  for /l %%i in (1,1,%w%) do (set t=!t!   )
  for /l %%d in (1,1,%d%) do (
    if %%d lss 10 (set t=!t! )
    set t=!t!%%d
    call :get_day_of_week %y% %m% %%d
    set n=!ERRORLEVEL!
    if !n! equ 6 (echo !t! & set t=) else (set t=!t! )
  )
  if not "%t%" == "" echo %t%
  echo.

  exit /b 0
endlocal
goto :EOF

:is_leap_year
setlocal
  set n=0

  set /a n=%1%%400
  if %n% equ 0 exit /b 1

  set /a n=%1%%100
  if %n% equ 0 exit /b 0

  set /a n=%1%%4
  if %n% equ 0 exit /b 1

  exit /b 0
endlocal
goto :EOF

:get_day_of_week
setlocal
  set y=%1
  set m=%2

  if %m% leq 2 (
    set /a y-=1
    set /a m+=12
  )

  :: ツェラーの公式
  set /a w=(5*%y%/4-%y%/100+%y%/400+(26*%m%+16)/10+%3)%%7
endlocal & exit /b %w%
goto :EOF

位置パラメーターの指定や実行結果は以下をご覧ください。

cal.png

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
1