LoginSignup
6
6

More than 5 years have passed since last update.

PHPでカレンダー出力

Posted at

PHPだと1日の曜日とか月末をdate()関数で一発で取ってこれるのが味噌
strtotime()も強い

cal.php
<?php
$col_width = 3;
$title_format = '-*- Y-m -*-';

// 引数がない場合は今月
$ts = strtotime("first day of");
if (isset($argv[2])) {
    $ts = strtotime("first day of {$argv[1]}-{$argv[2]}");
}
list($y, $m, $t, $w) = explode(',', date('Y,m,t,w', $ts));
// title
$title = str_replace(array('Y', 'm'), array($y, sprintf('%2d', $m)), $title_format);
echo str_repeat(' ', ($col_width * 7 - strlen($title)) / 2) . $title . PHP_EOL;
echo str_repeat(' ', $w * $col_width);
for ($i = 1; $i <= $t; $i++) {
    echo sprintf("%{$col_width}d", $i);
    if (($w + $i) % 7 == 0) {
        echo PHP_EOL;
    }
}
echo PHP_EOL;

出力

   -*- 2014-12 -*-
     1  2  3  4  5  6
  7  8  9 10 11 12 13
 14 15 16 17 18 19 20
 21 22 23 24 25 26 27
 28 29 30 31

6
6
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
6
6