PrimitiveType

PHP: command line calendar

This small PHP program prints the days of the current month. It is intended for use in a command line environment running Bash. The current day is highlighted using Bash colour codes. To run the script from Window's command prompt, remove or comment out the lines that highlight and un-highlight the text.

<?php $colWidth = 4; // can be changed // Print month and year echo date('F Y') . PHP_EOL; // Print days of the week header (Mo to Su) echo sprintf('Mo%1$sTu%1$sWe%1$sTh%1$sFr%1$sSa%1$sSu', str_repeat(' ', $colWidth - 2)) . PHP_EOL; // Values for today's date $currentDay = date('j'); $currentMonth = date('m'); $currentYear = date('Y'); // Number of days in the month $numDays = cal_days_in_month(CAL_GREGORIAN, $currentMonth, $currentYear); // Loop through all days in the month for ($day = 1; $day <= $numDays; $day++) { $dayOfWeek = date('N', mktime(0, 0, 0, $currentMonth, $day, $currentYear)); // 1 through 7 if ($day == 1) { // Print any leading spaces required for the first day of the month $spaces = ($dayOfWeek - 1) * $colWidth; echo str_repeat(' ', $spaces); } if ($day == $currentDay) { // Highlight the current day (32 is the code for green) echo "\033[32m"; } // Print the current day number plus required padding echo $day . ($day < 10 ? ' ' : '') . str_repeat(' ', $colWidth - 2); if ($day == $currentDay) { // Undo highlight echo "\033[0m"; } if ($dayOfWeek == 7) { // Start a new line after each Sunday echo PHP_EOL; } } echo PHP_EOL;

Sample output:

June 2018 Mo Tu We Th Fr Sa Su 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